第一个阵列:
[ { B:
[ {
name: '1-1-1',
},
{
name: '1-1-2',
} ],
name: '1-1', },
{ B:
[ {
name: '1-2-1',
},
{
name: '1-2-2',
} ],
name: '1-2',
} ]
第二阵列:
[{ A:
[{ name: '1-1',
B:
[{
name: '1-1-1',
},
{
name: '1-1-2',
}],
},
{ name: '1-2',
[{
name: '1-2-1',
},
{
name: '1-2-2',
}]
}],
name: '1',
}]
我希望最终输出是这样的:
var finalArray = []
_.each(firstArray, function(itemA) {
_.each(secondArray, function(itemB) {
if (itemB.name === itemA.name) {
itemA.B = itemB.B
//Fails here but if i do something like itemA.sjdc = 'skdjn' it comes successfully
}
})
finalArray.push(itemA)
})
我尝试使用map和filter但是我使用了太多for循环遍历每个并构建最终结果。有没有更简单的方法呢?
我试过的代码:
command = r"adb shell screencap -p"
proc = subprocess.Popen(shlex.split(command),stdout=subprocess.PIPE)
out = proc.stdout.read(30000000)
img = cv2.imdecode(out,cv2.IMREAD_COLOR)
if img is not None:
cv2.imshow("",img)
cv2.waitKey(0)
cv2.destroyWindow("")
答案 0 :(得分:1)
使用第二个数组的相应项更新第一个数组要容易得多。 Map用于获取具有父名称的对象。
var one = [{ A: [{ name: '1-1' }, { name: '1-2' }], name: '1' }],
two = [{ B: [{ name: '1-1-1' }, { name: '1-1-2', }], name: '1-1' }, { B: [{ name: '1-2-1' }, { name: '1-2-2', }], name: '1-2' }],
map = new Map(two.map(o => [o.name, o.B]));
one.forEach(({ A }) => A.forEach(o => o.B = map.get(o.name)));
console.log(one);
.as-console-wrapper { max-height: 100% !important; top: 0; }
通过创建新的独立数组来完成。
var one = [{ A: [{ name: '1-1' }, { name: '1-2' }], name: '1' }],
two = [{ B: [{ name: '1-1-1' }, { name: '1-1-2', }], name: '1-1' }, { B: [{ name: '1-2-1' }, { name: '1-2-2', }], name: '1-2' }],
map = new Map(two.map(o => [o.name, o.B]));
merged = one.map(o =>
Object.assign({}, o, { A: o.A.map(p =>
Object.assign({}, p, { B: map.get(p.name) })
) })
);
console.log(merged);
console.log(one);
console.log(two);
.as-console-wrapper { max-height: 100% !important; top: 0; }