我有一个包含如下对象的数组:
arr = [
{name: 'Igor', id: 1,....},
{name: 'Anton', id: 1,.... },
{name: 'Igor', id: 2,.... },
{name: 'Peter', id: 2,.... },
{name: 'Igor', id: 2,.... }
]
我需要获取新的数组,例如:
arrId = [
{ id: 1, names: 'Igor, Anton' },
{ id: 2, names: 'Igor, Peter' }
]
想不出好的解决办法
最佳答案
function rearrange(arr) {
// use `reduce` to build an object using the ids as keys
// this allows us to place all the names with the same id together
// note we pass in an empty object to act as our initial p argument.
var out = arr.reduce(function (p, c) {
var key = c.id, name = c.name;
// if the key doesn't exist create it and set its value
// to an empty array
p[key] = p[key] || [];
// add the name to the array if it doesn't already exist
if (p[key].indexOf(name) === -1) p[key].push(name);
return p;
}, {});
// use `map` to return an array of objects
return Object.keys(out).map(function (el) {
// make sure we use an integer for the id, and
// join the array to get the appropriate output
return { id: +el, names: out[el].join(', ') };
});
}
rearrange(arr);
输出
[
{
"id": 1,
"names": "Igor, Anton"
},
{
"id": 2,
"names": "Igor, Peter"
}
]
关于javascript - 带有对象变换的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34351086/