假设您有三个对象数组:
let a1 = [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'baz' }
]
let a2 = [
{ name: 'foo' },
{ name: 'bar' }
]
let a3 = [
{ name: 'bar' },
{ name: 'baz' }
]
目标是使用a1
作为来源,并在id
和a2
的元素中添加a3
字段,其中包含相应的name
字段a1
。什么是实现这一目标的有效方法? (注意:'高效'在这里意味着'比循环内循环更优雅'。
结果应如下所示:
a2: [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' }
]
a3: [
{ id: 2, name: 'bar' },
{ id: 3, name: 'baz' }
]
答案 0 :(得分:2)
您可以使用Map
来引用给定名称的ID。然后分配。
var a1 = [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }, { id: 3, name: 'baz' }],
a2 = [{ name: 'foo' }, { name: 'bar' }],
a3 = [{ name: 'bar' }, { name: 'baz' }],
map = new Map(a1.map(o => [o.name, o.id]));
[a2, a3].forEach(a => a.forEach(o => o.id = map.get(o.name)));
console.log(a2);
console.log(a3);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:2)
对于另一种答案,它可能是这样的。
它不包含循环,可能是答案中最短的代码。
const a1 = [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }, { id: 3, name: 'baz' }];
const a2 = [{ name: 'foo' }, { name: 'bar' }];
const a3 = [{ name: 'bar' }, { name: 'baz' }];
let f = x => a1.filter(a => x.some(y => y.name === a.name));
console.log(f(a2));
console.log(f(a3));

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)
a2.forEach((a2Elem) => a2Elem.id = a1.filter((a1Elem) => a1Elem.name === a2Elem.name)[0].id)
答案 3 :(得分:1)
我首先获取给定名称的索引,然后将要合并的数组映射到:
function combine(mergeInto, base) {
let indexes = base.map(e => e.name);
return mergeInto.map(e => ({
name: e.name,
id: base[indexes.indexOf(e.name)].id
}));
}
let a1 = [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'baz' }
]
let a2 = [
{ name: 'foo' },
{ name: 'bar' }
]
let a3 = [
{ name: 'bar' },
{ name: 'baz' }
]
function combine(mergeInto, base) {
let indexes = base.map(e => e.name);
return mergeInto.map(e => ({
name: e.name,
id: base[indexes.indexOf(e.name)].id
}));
}
console.log(combine(a3, a1));
答案 4 :(得分:0)
单循环提议 - 在数组中创建hash table
然后合并字段 - 演示如下:
let a1=[{id:1,name:'foo'},{id:2,name:'bar'},{id:3,name:'baz'}], a2=[{name:'foo'},{name:'bar'}], a3=[{name:'bar'},{name:'baz'}];
// create a hash table
let hash = a1.reduce(function(p,c){
p[c.name] = c;
return p;
},Object.create(null))
// merge the results
function merge(arr) {
Object.keys(arr).map(function(e){
arr[e]['id'] = hash[arr[e].name]['id'];
});
return arr;
}
console.log(merge(a2), merge(a3));

.as-console-wrapper{top:0;max-height:100%!important;}