![](/img/trans.png)
[英]How to find all matching keys and values of one object in array of objects?
[英]How to get values of all keys in array of objects with more than one keys and then sum of them all [on hold]
var arrayOfObjects = [ { value1: 50, }, { value2: 100, value3: 600 }, { value4: 500, value5: 700 } ]; for (var i = 0; i < arrayOfObjects.length; i++) { var key = Object.values(arrayOfObjects[i]); var sum = 0; for (var j = 0; j < key.length; j++) { var key = Object.values(arrayOfObjects[j]); var string = key[j]; var sum = sum + (string); console.log(key); } }
您可以將flatMap
與Object.values
結合使用,以獲得所有值的扁平數組。 然后你可以將它們與reduce
相加:
var arrayOfObjects = [ { value1: 50, }, { value2: 100, value3: 600 }, { value4: 500, value5: 700 } ]; var total = arrayOfObjects.flatMap(Object.values).reduce((a, b) => a + b, 0); console.log(total);
使用減少
var arrayOfObjects = [
{ value1: 50, },
{ value2: 100, value3: 600 },
{ value4: 500, value5: 700 }
];
const sum = arrayOfObjects.reduce((total, current) => {
const values = Object.values(current);
return values.length > 1 ? values.reduce((last, next) => last + next, 0) + total : total
}, 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.