javascript - 将对象数组减少为键值对映射,保留值数组中的重复条目

标签 javascript arrays maps mapping

我需要减少对象数组,但减少对象中的特定 key 属性,并将具有相同 key 值的所有对象放入一个数组中在关联的 value 数组中。

我需要的示例:

对象

var obj1 = {
  name: "server1",
  type: "http",
  port: "8080"
}

var obj2 = {
  name: "server2",
  type: "https",
  port: "8443"
}

var obj3 = {
  name: "server3",
  type: "http",
  port: "80"
}

// Place objects in an array (as interm step)
var array = [obj1, obj2, obj3];

使用上面的代码,我尝试了

var map = new Map(array.map(server => [server.type, server]));

但这最终给了我:

0: {"http" => Object}
    key: "http"
    value:
        name: "server3"
        port: "80"
        type: "http"
1: {"https" => Object}
    key: "https"
    value:
        name: "server2"
        port: "8443"
        type: "https"

但是我需要是:

0: {"http" => Object}
    key: "http"
    value:[ 
        {
            name: "server1"
            port: "8080"
            type: "http"
        },
        {
            name: "server3"
            port: "80"
            type: "http"
        },
1: {"https" => Object}
    key: "https"
    value:
        name: "server2"
        port: "8443"
        type: "https"

因此,我可以遍历每个类型,找到所有唯一值,以此作为类型创建每个对象的列表,然后将其添加到映射中,但这对于一个简单的任务来说似乎太多了。

有没有更快/更方便的方法来缩短这个时间?

最佳答案

我不确定 map 在这里是否合适。您可以使用简单的 forEach 并检查当前键是否已存在于数组中。如果没有,则使用当前项目创建一个新对象并检查下一个。

类似这样的事情:

var obj1 = {
  name: "server1",
  type: "http",
  port: "8080"
}

var obj2 = {
  name: "server2",
  type: "https",
  port: "8443"
}

var obj3 = {
  name: "server3",
  type: "http",
  port: "80"
}

// Place objects in an array (as interm step)
var array = [obj1, obj2, obj3];

let output = {};
array.forEach((item) => {
  // the item does not exists, we create it.
  if(!output[item.type]) {
    output[item.type] = {key: item.type, value: []};
  }
  // in either case, we push the current item in the value.
  // of the current output key.
  output[item.type].value.push(item);
});

// we are using Object.values() because we do not want the keys
// used to generate the output.
console.log(Object.values(output));

关于javascript - 将对象数组减少为键值对映射,保留值数组中的重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59879085/

相关文章:

javascript - 使用 Google map 地理定位标记多个位置

r - 如何将连续的颜色图例添加到用 map 制作的 R map

javascript - 如何创建一个 HTML 模块

javascript - 如何将 icomoon 图标添加到 Canvas ?

java - 从数组中检索特定范围的数据 (Java)

c - 将地址分配给 C 中的结构数组

java - 使用现有 GoogleMap API 的 Android MapView

javascript - bootstrap selectpicker knockoutjs 禁用选项

javascript - javascript中如何定义全局变量

ios - Swift - 数组过滤器不删除对象