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

标签 javascript arrays json object

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

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/

相关文章:

Python列表错误,列表索引超出范围

PHP:数组有最大尺寸吗?

python - 无法从 JSON 反序列化 PyMongo ObjectId

javascript - 去掉JSON中的重复对象,组成数组

javascript - react Hook : paradigm transition problem from sync to async

javascript - react : Why <Input> puts the event object at the end of the argument of the event handler

javascript - 覆盖 jest-junit 默认输出位置?

javascript - ReactJs 元素类型无效 检查渲染方法

javascript 序列化 - 一个简短的库

asp.net - 在 ajax 调用中处理过期的 .NET Forms 身份验证 cookie 的最佳方法?