[英]Sum up arrays of an array of object
I have the following array with objects, and the object consists of an array.我有以下带有对象的数组,该对象由一个数组组成。 I would like to return the total length of the array "species".
我想返回数组“物种”的总长度。
let fish = [
{
"name": "salmon",
"species": [
{
"name": "atlantic salmon",
"gender": "male"
},
{
"name": "sockeye salmon",
"gender": "female"
},
],
},
{
"name": "carp",
"species": [
{
"name": "grass carp",
"gender": "male"
},
{
"name": "common carp",
"gender": "female"
},
],
},
]
I would like to get back a result of 4 from this but I'm not too sure how.我想从中得到 4 的结果,但我不太确定如何。 Any suggestions?
有什么建议? Thanks!
谢谢!
Try this line.试试这条线。 It works fine.
它工作正常。
let fish = [
{
"name": "salmon",
"species": [
{
"name": "atlantic salmon",
"gender": "male"
},
{
"name": "sockeye salmon",
"gender": "female"
},
],
},
{
"name": "carp",
"species": [
{
"name": "grass carp",
"gender": "male"
},
{
"name": "common salmon",
"gender": "female"
},
],
},
];
const speciesCount = fish.flatMap(f => f.species).length;
console.log(speciesCount);
You could use .reduce
to accumulate the length of species
您可以使用
.reduce
来累积species
的长度
const res = fish.reduce((acc, el) => acc + el.species.length, 0)
let fish = [ { name: "salmon", species: [ { name: "atlantic salmon", gender: "male", }, { name: "sockeye salmon", gender: "female", }, ], }, { name: "carp", species: [ { name: "grass carp", gender: "male", }, { name: "common salmon", gender: "female", }, ], }, ] const res = fish.reduce((acc, el) => acc + el.species.length, 0) console.log(res)
Try this.尝试这个。
let count = 0;
for (let i = 0; i < fish.length; i++) {
for (let j = 0; j < fish[i][species].length; i++) {
count++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.