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

时间:2019-02-22 05:18:12

标签: javascript arrays

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

data = [json.loads(line) for line in open('tweets.json', 'r')]

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

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

结果为7。

如果我不知道所有键,如何以一种干净的方式进行操作?

7 个答案:

答案 0 :(得分:3)

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

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

console.log(Object.values(arr).flat().length);

答案 1 :(得分:2)

您可以使用object.valuesreduce

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)

答案 2 :(得分:0)

使用减少 。获取对象中的所有值,并减少一一添加数组的长度

var arr = {
  names: ['John', 'Paul'],
  phones: ['iPhone', 'Samsung', 'Huawei'],
  clothesBrands: ['HM', 'Zara']
}
console.log(Object.values(arr).reduce((acc, e) => acc += e.length, 0))

答案 3 :(得分:0)

在循环中,使用对象时是您的朋友。 以下示例可解决您的问题:

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

希望这会有所帮助。

答案 4 :(得分:0)

您可以在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);

答案 5 :(得分:0)

为此,您应该使用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);

答案 6 :(得分:0)

这里还有另一种使用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);

相关问题