以下是变量:
pip.exe
let linked = {
related: [
[0, 'a', 'b'],
[0, 'c', 'd', 'e', 'f', 'g'],
[0, "s"],
[0, 'd'],
[0, 'g', 'n', 'h']
]
}
let hold = [{
0: 4, // 0 represents [0,'a','b']
1: 3 // 1 represents [0,'c','d','e','f','g']
},
{
3: 2, // 3 represents [0,'d']
4: 6 // 4 represents [0,'g','n', 'h']
}
];
包含两个对象,每个对象的属性表示hold array
的索引。
问题是我想将每个link.related
属性的值添加到hold object
的第一个元素中。
所以结果应该是:
linked.related
所以我想用let linked = {
related: [
[4, 'a', 'b'],
[3, 'c', 'd', 'e', 'f', 'g'],
[0, "s"],
[2, 'd'],
[6, 'g', 'n', 'h']
]
}
的第一个元素求和值
答案 0 :(得分:2)
您可以使用forEach
和Object.entries
let linked = {related: [[0, 'a', 'b'],[0, 'c', 'd', 'e', 'f', 'g'],[0, "s"],[0, 'd'],[0, 'g', 'n', 'h']]}
let hold =[{0: 4, 1:3},{3: 2, 4:6}]
hold.forEach(v => {
Object.entries(v).forEach(([k, v]) => {
linked.related[k][0] += v
})
})
console.log(linked)
答案 1 :(得分:2)
您可以迭代保留并获取更新的条目。
var linked = { related: [[0, 'a', 'b'], [0, 'c', 'd', 'e', 'f', 'g'], [0, "s"], [0, 'd'], [0, 'g', 'n', 'h']] },
hold = [{ 0: 4, 1: 3 }, { 3: 2, 4: 6 }];
hold.forEach(o => Object.entries(o).forEach(([i, v]) => linked.related[i][0] += v));
console.log(linked);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:2)
您可以在2个forEach循环中完成
hold.forEach(x => {
Object.keys(x).forEach (y => {
linked.related[y][0] += x[y]
});
});
let linked = {
related: [
[0, 'a', 'b'],
[0, 'c', 'd', 'e', 'f', 'g'],
[0, "s"],
[0, 'd'],
[0, 'g', 'n', 'h']
]
}
let hold = [{
0: 4,
1: 3
},
{
3: 2,
4: 6
}
];
hold.forEach(x => {
Object.keys(x).forEach (y => {
linked.related[y][0] += x[y]
});
});
console.log(linked.related);