[英]How to sum lengths of array properties inside an object
我有一個看起來像這樣的對象:
let arr = { names: ['John', 'Paul'], phones: ['iPhone', 'Samsung', 'Huawei'], clothesBrands: ['HM', 'Zara'] }
我需要對數組的長度求和。 我可以這樣:
arr.names.length + arr.phones.length + arr.clothesBrands.length
結果是7。
如果我不知道所有鍵,如何以一種干凈的方式進行?
您可以檢查.flat
數組值的長度:
const arr = { names: ['John', 'Paul'], phones: ['iPhone', 'Samsung', 'Huawei'], clothesBrands: ['HM', 'Zara'] }; console.log(Object.values(arr).flat().length);
您可以使用object.values並減少
Object.values
將為您提供Object中的所有值,並reduce
我們計算的總長度。
let obj = {names: ['John', 'Paul'], phones: ['iPhone', 'Samsung', 'Huawei'], clothesBrands: ['HM', 'Zara']} let op = Object.values(obj).reduce( (out, inp) => out + inp.length, 0) console.log(op)
使用減少。 獲取對象中的所有值,並減少一一添加數組的長度
var arr = { names: ['John', 'Paul'], phones: ['iPhone', 'Samsung', 'Huawei'], clothesBrands: ['HM', 'Zara'] } console.log(Object.values(arr).reduce((acc, e) => acc += e.length, 0))
對於in循環,使用對象時是您的朋友。 以下示例可解決您的問題:
var arr = {names: ['John', 'Paul'], phones: ['iPhone', 'Samsung', 'Huawei'], clothesBrands: ['HM', 'Zara'], hello: 1}; var totalLength = 0; for(var char in arr){ // Confirm that the key value is an array before adding the value. if(Array.isArray(arr[char])){ totalLength += arr[char].length; } } console.log(totalLength);
希望這會有所幫助。
您可以在Object.values
上使用Array.prototype.reduce()
並通過Array.isArray()
檢查該值是否為數組
let obj ={names: ['John', 'Paul'], phones: ['iPhone', 'Samsung', 'Huawei'], clothesBrands: ['HM', 'Zara']} let sum = Object.values(obj).reduce((ac,a) => { return Array.isArray(a) ? ac + a.length : ac },0) console.log(sum);
您應該為此使用Array.reduce
。
const arr = {names: ['John', 'Paul'], phones: ['iPhone', 'Samsung', 'Huawei'], clothesBrands: ['HM', 'Zara']}; const sum = Object.values(arr).reduce((acc, {length}) => { return acc = length ? acc+ length : acc; }, 0); console.log(sum);
在這里,您還有另一種使用for ... in直接迭代對象keys
:
let arr = { names: ['John', 'Paul'], phones: ['iPhone', 'Samsung', 'Huawei'], clothesBrands: ['HM', 'Zara'] } let totalLen = 0; for (k in arr) { Array.isArray(arr[k]) && (totalLen += arr[k].length); } console.log(totalLen);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.