猿问

合并数组内的JSON对象

我有一个JSON数组如下


[

{"Name" : "Arrow",

"Year" : "2001"

},


{"Name" : "Arrow",

"Type" : "Action-Drama"

},

{ "Name" : "GOT",

"Type" : "Action-Drama"

}

]

我正在尝试将其转换为


[

  { 

    "Name" : "Arrow",

    "Year" : "2001",

    "Type" : "Action-Drama",

  },

  {

   "Name" : "GOT",

   "Type" : "Action-Drama"

  }

]

任何帮助,不胜感激。


红颜莎娜
浏览 205回答 3
3回答

精慕HU

您可以使用reduce()和findIndex()let data = [{"Name" : "Arrow","Year" : "2001"},{"Name" : "Arrow","Type" : "Action-Drama"},{ "Name" : "GOT","Type" : "Action-Drama"}]let res = data.reduce((ac,a) => {  let ind = ac.findIndex(x => x.Name === a.Name);  ind === -1 ? ac.push({...a}) : ac[ind] = {...ac[ind],...a};  return ac;},[])console.log(res)

慕的地8271018

使用reduce和Object.assign合并数组中的项目:const data = [{  "Name" : "Arrow",  "Year" : "2001"}, {  "Name" : "Arrow",  "Type" : "Action-Drama"}, {  "Name" : "GOT",  "Type" : "Action-Drama"}];function mergeByProp (prop, xs) {  return xs.reduce((acc, x) => {    if (!acc[x[prop]]) {      acc[x[prop]] = x;    } else {      acc[x[prop]] = Object.assign(acc[x[prop]], x);    }    return acc;  }, {});}function objToArr (obj) {  return Object.keys(obj).map(key => obj[key]);}console.log(objToArr(mergeByProp('Name', data)));
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答