javascript - 我想合并数组中的值(如果它们具有相同的 id)

标签 javascript

我有一个数组对象,它具有相同的 Id 和不同的值。我需要一个具有相同 id 和合并到 id 的不同值的输出。

输入:

let data = [{
    id: 1,
    value: 'Honda'
  },
  {
    id: 2,
    value: 'Fiat'
  },
  {
    id: 2,
    value: 'Porche'
  },
  {
    id: 1,
    value: 'Benz'
  }
];

输出:

result = [{
      id: 1,
      value: ['Honda', 'Benz']
    }, {
      id: 2,
      value: ['Fiat', 'Porche']
    }

最佳答案

希望对您有帮助。但这个问题是重复的

let data = [{
    id: 1,
    value: 'Honda'
  },
  {
    id: 2,
    value: 'Fiat'
  },
  {
    id: 2,
    value: 'Porche'
  },
  {
    id: 1,
    value: 'Benz'
  }
];

var output = [];

data.forEach(function(item) {
  var existing = output.filter(function(v, i) {
    return v.id == item.id;
  });
  if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    output[existingIndex].value = output[existingIndex].value.concat(item.value);
  } else {
    if (typeof item.value == 'string')
      item.value = [item.value];
    output.push(item);
  }
});

console.dir(output);

关于javascript - 我想合并数组中的值(如果它们具有相同的 id),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57253083/

相关文章:

javascript - 切换多个跨度

javascript - 使用 querySelector 查找包含在同级行中的下一个单元格

javascript - D3.js 无法从 json 文件渲染我的圈子

javascript - 使用正则表达式在 $ 符号之前获取数字

javascript - 如何通过特权代码使用 Dom File API?

javascript - 如何更新混淆代码中的变量

javascript - 如何通过 ID 从 Backbone.js 集合中获取模型?

javascript - 谷歌登录没有反应

javascript - 有没有办法为 1 个请求设置 cookie?

javascript - jQuery 动态 DOM 创建性能