gpt4 book ai didi

javascript - 如何在两个不同的数组上获得总长度或计数

转载 作者:行者123 更新时间:2023-12-02 16:09:26 25 4
gpt4 key购买 nike

我知道这个问题很难理解,所以我会解释我希望它如何我有这个数据数组:

const products = [
{
name: "Product A",
reviews: [
{
comment: "Good Product",
username: "Alif",
},
],
},
{
name: "Product B",
reviews: [
{
comment: "Bad Product",
username: "Alif",
},
{
comment: "Good Product",
username: "Atif",
},
{
comment: "Ok Product",
username: "Esha",
},
],
},
];


products.map(({ reviews }) => {
console.log(reviews.length);
});

我想获得评论的长度,但由于两个对象是分开的,即产品 A 和产品 B,我得到分开的长度或像这样计数:

enter image description here

我希望结果是总长度为 4 或计数为 4,所以我想到了合并数组。还有其他方法吗?

最佳答案

一个天真的解决方案可能是:

const products = [{
name: "Product A",
reviews: [{
comment: "Good Product",
username: "Alif",
}, ],
},
{
name: "Product B",
reviews: [{
comment: "Bad Product",
username: "Alif",
},
{
comment: "Good Product",
username: "Atif",
},
{
comment: "Ok Product",
username: "Esha",
},
],
},
];

const allProducts = products.flatMap(({
reviews
}) => reviews);

console.log(allProducts.length);

这会映射每个产品并提取评论数组,然后将其扁平化为一个数组。

关于javascript - 如何在两个不同的数组上获得总长度或计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68429378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com