如果它具有相同的 ID,我想将值合并到数组中。 我有一组这样的对象。
[
{
id: 'Tony',
type: 'hero',
favorite: 'Rosie',
},
{
id: 'Jane',
type: 'human',
favorite: null,
},
{
id: 'Tony',
type: 'hero',
favorite: 'Lisa',
},
{
id: 'Steve',
type: 'hero',
favorite: 'Jennie',
},
{
id: 'Tony',
type: 'hero',
favorite: 'Jisoo',
},
]
我想将字符串中的键 favorite
合并到数组中。
我想要这样的输出
[
{
id: 'Tony',
type: 'hero',
favorite: ['Rosie', 'Lisa', 'Jisoo'],
},
{
id: 'Jane',
type: 'human',
favorite: null,
},
{
id: 'Steve',
type: 'hero',
favorite: ['Jennie'],
}
我试着写这样的代码:(来自:Sum similar keys in an array of objects)
var obj = [
{
id: 'Tony',
type: 'hero',
favorite: 'Rosie',
},
{
id: 'Jane',
type: 'human',
favorite: null,
},
{
id: 'Tony',
type: 'hero',
favorite: 'Lisa',
},
{
id: 'Steve',
type: 'hero',
favorite: 'Jennie',
},
{
id: 'Tony',
type: 'hero',
favorite: 'Jisoo',
},
];
var holder = {};
const ar = []
obj.forEach(function (d) {
if (holder.hasOwnProperty(d.id)) {
holder[d.id] = ar.push(holder[d.id] + d.favorite);
} else {
holder[d.id] = d.favorite;
}
});
var obj2 = [];
for (var prop in holder) {
obj2.push({ name: prop, favorite: holder[prop] });
}
console.log(obj2);
但输出是
[ { name: 'Tony', favorite: 2 },
{ name: 'Jane', favorite: null },
{ name: 'Steve', favorite: 'Jennie' } ]
我该怎么做?
最佳答案
您可以使用单个 Array.reduce 来完成此操作并且很可能是最简单和最高效的方法:
var data = [ { id: 'Tony', type: 'hero', favorite: 'Rosie', }, { id: 'Jane', type: 'human', favorite: null, }, { id: 'Tony', type: 'hero', favorite: 'Lisa', }, { id: 'Steve', type: 'hero', favorite: 'Jennie', }, { id: 'Tony', type: 'hero', favorite: 'Jisoo', }, ]
let result = data.reduce((r, {id,type,favorite}) => {
r[id] = r[id] || {id, type, favorite: []}
r[id].favorite.push(favorite)
return r
}, {})
console.log(Object.values(result))
想法是按 id
“分组”,然后在每次迭代时继续推送到 favorites
数组。
对于 ES5
你可以用类似的方式来做:
var data = [ { id: 'Tony', type: 'hero', favorite: 'Rosie', }, { id: 'Jane', type: 'human', favorite: null, }, { id: 'Tony', type: 'hero', favorite: 'Lisa', }, { id: 'Steve', type: 'hero', favorite: 'Jennie', }, { id: 'Tony', type: 'hero', favorite: 'Jisoo', }, ]
let result = data.reduce(function(r, c){
r[c.id] = r[c.id] || {id: c.id, type: c.type, favorite: []}
r[c.id].favorite.push(c.favorite)
return r
}, {})
console.log(Object.values(result))
确实不需要 lodash
来实现这一点。
关于javascript - 如果具有相同的 id,如何将数组对象值合并到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56160615/