通过相同的键值合并对象数组

时间:2018-08-31 18:29:36

标签: javascript arrays json for-loop javascript-objects

我有一个这样的对象数组:

[
  {
    "name": "Blah",
    "description": "This is a description"
  },
  {
    "name": "Foo",
    "description": "This is a description"
  },
  {
    "name": "Bar",
    "description": "This is a description"
  },
  {
    "name": "Blah",
    "description": "This is a description"
  },
  {
    "name": "Test",
    "description": "This is a description"
  }
]

我想运行某种功能,以description1 + "\n" + description2模式组合具有相同名称的对象,因此最终结果是:

[
  {
    "name": "Foo",
    "description": "This is a description"
  },
  {
    "name": "Bar",
    "description": "This is a description"
  },
  {
    "name": "Blah",
    "description": "This is a description\nThis is a description"
  },
  {
    "name": "Test",
    "description": "This is a description"
  }
]

不需要保留数组的顺序。任何帮助,将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用查找对象查找重复项:

 const result = [], hash = {};
 for(const {name, description} of input) {
    if(hash[name]) {
      hash[name].description += "\n" + description;
    } else {
      result.push(hash[name] = { name, description });
   }
 }

答案 1 :(得分:1)

您可以简单地使用Array.reduce()来创建地图,按名称分组,并且地图上的Object.values()将为您提供所需的结果:

let arr = [ { "name": "Blah", "description": "This is a description" }, { "name": "Foo", "description": "This is a description" }, { "name": "Bar", "description": "This is a description" }, { "name": "Blah", "description": "This is a description" }, { "name": "Test", "description": "This is a description" } ];
let result = Object.values(arr.reduce((a, {name,description})=>{
  if(a[name])
    a[name].description += "\n" + description;
   else
    a[name] = Object.assign({},{name,description});
   return a;
},{}));
console.log(result);

答案 2 :(得分:1)

您可以使用reduce和findIndex来检查新数组是否具有名称匹配的任何对象。如果是这样,请更新说明

let orgArray = [{
    "name": "Blah",
    "description": "This is a description"
  },
  {
    "name": "Foo",
    "description": "This is a description"
  },
  {
    "name": "Bar",
    "description": "This is a description"
  },
  {
    "name": "Blah",
    "description": "This is a description"
  },
  {
    "name": "Test",
    "description": "This is a description"
  }
]

let newArray = orgArray.reduce(function(acc, curr) {
  let findIndexs = acc.findIndex(function(item) {
    return item.name === curr.name;

  })
  if (findIndexs === -1) {
    let obj = {
      name: curr.name,
      description: curr.description
    }
    acc.push(obj)
  } else {
    acc[findIndexs].description = acc[findIndexs].description + ' \n ' + curr.description
  }
  return acc;
}, []);
console.log(newArray)