对象数组查找键名并合并值

时间:2020-03-19 11:26:58

标签: javascript node.js

我的数组是:

array = [{
  "name": "obj0_property0",
  "url": "picture1"
}, {
  "name": "obj1_property0",
  "url": "picture1"
}, {
  "name": "obj0_property1",
  "url": "picture2"
}]

我想要在JavaScript中这样输出:

array[{
  "obj0": ["picture1","picture2"]
}, {
  "obj1": ["picture1"]
}]

我想找到数组键名obj0obj1并合并图片值

3 个答案:

答案 0 :(得分:3)

reduce是一种转换数组的好方法

var array = [{"name":"obj0_property0","url":"picture1"},{"name":"obj1_property0","url":"picture1"},{"name":"obj0_property1","url":"picture2"}]

var result = array.reduce((acc, {name, url}) => {
  // getting object key obj0, obj1
  const objKey = name.split(`_`)[0];
  
  // trying to find in accumulator object with same key as objKey
  const objInArray = acc.find(accitem => objKey in accitem);

  // if found
  if (objInArray) {
    // add another url
    objInArray[objKey].push(url)
  } else {
    // if not found add new object
    acc.push({[objKey]: [url]})
  }
  return acc;
}, []) // [] is initial value of accumulator

console.log(result)

// array [{"obj0":"picture1","picture2"},{"obj1":"picture1"}]

答案 1 :(得分:2)

您可以use reduce method并将所有url存储在数组中:

const result = Object.entries(array.reduce((a, {name, url})=> {
    let key = name.substring(0, 4);
    a[key] = a[key] || [];
    a[key].push(url);
    return a;
},{})).map(([k, v])=> ({[k]: v}));

一个例子:

let array = [
    {"name":"obj0_property0","url":"picture1"},
    {"name":"obj1_property0","url":"picture1"},
    {"name":"obj0_property1","url":"picture2"}
];

const result = Object.entries(array.reduce((a, {name, url})=> {
    let key = name.substring(0, 4);
    a[key] = a[key] || [];
    a[key].push(url);
    return a;
},{})).map(([k, v])=> ({[k]: v}));
console.log(result);

答案 2 :(得分:1)

简单的collection2可以很容易地重新组合源数组:

presentInCollection2
MongoDB