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

Tom*_*omb 0 javascript arrays

我有一个看起来像这样的对象:

let arr = {
  names: ['John', 'Paul'],
  phones: ['iPhone', 'Samsung', 'Huawei'],
  clothesBrands: ['HM', 'Zara']
}
Run Code Online (Sandbox Code Playgroud)

我需要对数组的长度求和。我可以这样做:

arr.names.length + arr.phones.length + arr.clothesBrands.length 
Run Code Online (Sandbox Code Playgroud)

结果是7。

如果我不知道所有的键,我怎么能以干净的方式做到这一点?

Cer*_*nce 5

您可以检查.flatTened 值数组的长度:

const arr = {
  names: ['John', 'Paul'],
  phones: ['iPhone', 'Samsung', 'Huawei'],
  clothesBrands: ['HM', 'Zara']
};

console.log(Object.values(arr).flat().length);
Run Code Online (Sandbox Code Playgroud)