[英]Get cumulative length of array inside array of objects
I have been searching for quite a while but cannot find an answer to my issue.我一直在寻找很长一段时间,但找不到我的问题的答案。 The problem is pretty simple;
问题很简单; I have an array of objects, each containing another array of objects.
我有一个对象数组,每个对象都包含另一个对象数组。 I want to get the cumulative length of all arrays inside all objects.
我想获取所有对象内所有 arrays 的累积长度。
Here is some sample data:以下是一些示例数据:
const items = [
{
id: 1,
title: "Test 1",
data: [
{
...
},
{
...
},
]
},
{
id: 2,
title: "Test 2",
data: [
{
...
},
]
}
]
In this sample, the length should be 3 since there is 2 objects inside the first object's data property and 1 object inside the second object's data property.在此示例中,长度应为 3,因为第一个对象的数据属性中有 2 个对象,第二个对象的数据属性中有 1 个 object。
pretty simple很简单
const items = [ { id: 1, title: "Test 1", data: [{a:1},{a:1} ] }, { id: 2, title: "Test 2", data: [{a:1},{a:1},{a:1},{a:1}] } ] console.log('cumulative length ', items.reduce((a,c)=>a+c.data.length,0) )
All you need to do is loop through all items you got, check the length of the data
array of each item and add that length to a variable.您需要做的就是遍历您获得的所有项目,检查每个项目的
data
数组的长度并将该长度添加到变量中。 Here is a working snippet:这是一个工作片段:
const items = [ { id: 1, title: "Test 1", data: [ { }, { }, ] }, { id: 2, title: "Test 2", data: [ { }, ] } ]; // Initialize the count variable as 0 var count = 0; // Pass through each item items.forEach((item)=>{ // Adding the count of data of each item count += item.data.length; }); // Outputting the count console.log(count);
If you want to use for of loop that works too.如果你想使用 for of 循环也可以。
const countObjects = (arrayInput) => {
let totalCount = 0
for(let item of items) {
totalCount += item.data.length
}
return totalCount
}
console.log(countObjects(items))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.