我要更改此对象:
{
item1: 6,
item2: {
item3: 1,
item4: 1
},
item4: 1,
item5: {
item3: 1,
item1: 3
}
}
对该对象:
{
item1: 9,
item3: 2,
item4: 2
}
因此,从每个对象获取所有键:值,并将所有值插入并求和在一个对象中
我的实际代码:
function calculate_recipe(item, quantity) {
if (json.options[item].material) {
return quantity;
} else {
let crafting_quantity = json.craftable[item].quantity
let ingredients = json.craftable[item].ingredients
let items_needed = {}
for (let ingredient in ingredients) {
let ingredient_quantity = ingredients[ingredient]
items_needed[ingredient] = calculate_recipe(ingredient, Math.ceil(quantity / crafting_quantity) * ingredient_quantity);
}
return items_needed
}
}
return items_needed
返回我之前显示的第一个对象。
答案 0 :(得分:1)
您可以对嵌套对象进行递归调用,然后返回平面对象。
function getFlatSum(object, map = new Map) {
Object.entries(object).forEach(([k, v]) => {
if (v && typeof v === 'object') {
getFlatSum(v, map);
} else {
map.set(k, (map.get(k) || 0) + v);
}
});
return Object.assign({}, ...Array.from(map, ([k, v]) => ({ [k]: v })));
}
var data = { item1: 6, item2: { item3: 1, item4: 1 }, item4: 1, item5: { item3: 1, item1: 3 } },
result = getFlatSum(data);
console.log(result);