我的数组是:
array = [{
"name": "obj0_property0",
"url": "picture1"
}, {
"name": "obj1_property0",
"url": "picture1"
}, {
"name": "obj0_property1",
"url": "picture2"
}]
我想要在JavaScript中这样输出:
array[{
"obj0": ["picture1","picture2"]
}, {
"obj1": ["picture1"]
}]
我想找到数组键名obj0
和obj1
并合并图片值
答案 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