javascript - 如何对对象内数组属性的长度求和

标签 javascript arrays

我有一个如下所示的对象:

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);

关于javascript - 如何对对象内数组属性的长度求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54820496/

相关文章:

javascript - 如何将数组的新属性添加到现有的 json 数据中

javascript - 类型错误 : Cannot read property 'toLocaleLowerCase' of undefined

javascript - 当函数完成时(包括setTimeout(s))调用函数

javascript - 如何更改嵌套对象数组中的键值javascript

javascript - Array sort() 在分配给另一个数组后对实际数组列表进行排序

arrays - 如何获取静态数组的长度?

PHP CodeIgniter - 当关系表(不同表中有相同的列名)时如何获得良好的结果数组

javascript - 在每个路由调用上执行中间件

javascript - 如何获取父div data-id

javascript - 将 delay(0) 与 refCount() 结合使用