我有两个类似的对象:
letter number
------ -------
a 2
a 0
c 1
c 0
c 2
我想创建一个新对象并对每个键的每个值求和。像这样:
let data = [[
{
10: {key1: 1, key2: 2, key3: 3},
11: {key1: 1, key2: 2, key3: 3},
12: {key1: 1, key2: 2, key3: 3},
},
{},
{}
],
[
{
10: {key1: 1, key2: 2, key3: 3},
11: {key1: 1, key2: 2, key3: 3},
12: {key1: 1, key2: 2, key3: 3},
},
{},
{}
]]
每个对象中都有三个对象。在这三个对象中,有45个键,每个键都有一个具有三个键/值的对象。
我无法找到任何好的解决方案来总结每一个价值。
我目前的解决方案是首先通过let newData = [
{
10: {key1: 2, key2: 4, key3: 6},
11: {key1: 2, key2: 4, key3: 6},
12: {key1: 2, key2: 4, key3: 6},
},
{},
{}
]
循环:
data
在最坏的情况下,数据有三个对象,每个对象有45个键。然后我必须这样做三次。这看起来真的很糟糕。肯定有更好的办法。提示?
答案 0 :(得分:1)
您可以使用Array#reduce
并在添加值后映射内部数组的值。
var data = [[{ 10: { key1: 1, key2: 2, key3: 3 }, 11: { key1: 1, key2: 2, key3: 3 }, 12: { key1: 1, key2: 2, key3: 3 }, }, {}, {}], [{ 10: { key1: 1, key2: 2, key3: 3 }, 11: { key1: 1, key2: 2, key3: 3 }, 12: { key1: 1, key2: 2, key3: 3 }, }, {}, {}]],
result = data.reduce((a, b) =>
a.map((v, i) =>
(Object.keys(b[i]).forEach(k =>
Object.keys(b[i][k]).forEach(l =>
v[k][l] = (v[k][l] || 0) + b[i][k][l]))
, v)
)
);
console.log(result);

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

答案 1 :(得分:1)
以下是SteamVR_TrackedObject.index
和少量GetComponent<SteamVR_TrackedObject>().index = (SteamVR_TrackedObject.EIndex)index;
循环的解决方案,因为您还需要循环嵌套对象。
reduce()