简体   繁体   English

如何遍历两个 arrays 对象并获得修改了一些数据的新数组?

[英]How to loop through two arrays of objects and get a new array with some data modified?

How to loop through two arrays of objects and get a new array with some data modified?如何遍历两个 arrays 对象并获得修改了一些数据的新数组?

Arrays: Arrays:

  const products = [
    {
      brand: 'Levis',
      category: 'Jeans',
    },
    {
      brand: 'Levis',
      category: 'Jeans',
    },
    {
      brand: 'Levis',
      category: 'Tees',
    },
  ];


  const categories = [
    {
      name: 'Jeans',
    },
    {
      name: 'Tees',
    },
  ];

Need new categories array like this with new prop productCount :需要像这样使用新道具productCount的新类别数组:

  const newCategories = [
    {
      name: 'Jeans',
      productCount: 2,
    },
    {
      name: 'Tees',
      productCount: 0,
    },
  ];

I tried this way but it doesn't work:我试过这种方式,但它不起作用:

  const newArr = categories.map((category) => {
    let count = 0;

    const index = products.findIndex((product) => category.name === product.category);

    if (index > -1) {
      return {
        ...category,
        productCount: count++,
      };
    }

    return {
      ...category,
      productCount: 0,
    };
  });

Increasing the count number will not in that case because it will always start with zero.在这种情况下不会增加计数,因为它总是从零开始。 Instead, you can use the filter() method to find the number of products with a specific category and assign this number to productCount attribute.相反,您可以使用filter()方法查找具有特定类别的产品数量,并将此数量分配给productCount属性。

 const products = [{ brand: 'Levis', category: 'Jeans', }, { brand: 'Levis', category: 'Jeans', }, { brand: 'Levis', category: 'Tees', }, ]; const categories = [{ name: 'Jeans', }, { name: 'Tees', }, ]; const newArr = categories.map((category) => { const numberOfItems = products.filter((product) => category.name === product.category); return {...category, productCount: numberOfItems.length, }; }); console.log(newArr)

You can create an object and the transform it to array, something like this:您可以创建一个 object 并将其转换为数组,如下所示:

 const products = [ { brand: "Levis", category: "Jeans" }, { brand: "Levis", category: "Jeans" }, { brand: "Levis", category: "Tees" } ]; const categoriesObj = {}; products.forEach(({ brand, category }) => { categoriesObj[category]??= { name: category, productCount: 0 }; ++categoriesObj[category].productCount; }); const newCategories = Object.values(categoriesObj); console.log(newCategories);

You can use the Array#Map method and add a productCount property using the Array#filter method您可以使用Array#Map方法并使用Array#filter方法添加productCount属性

 const products = [{ brand: 'Levis', category: 'Jeans', }, { brand: 'Levis', category: 'Jeans', }, { brand: 'Levis', category: 'Tees', }, ]; const categories = [{ name: 'Jeans', }, { name: 'Tees', }, ]; const newCategories = [...categories].map(category => ({...category, productCount: products.filter(product => product.category === category.name).length })) console.log(newCategories)

You could do this with Array.reduce() , incrementing the productCount for each item.您可以使用Array.reduce()执行此操作,为每个项目增加 productCount。 This should also be efficient, requiring only one iteration of the products array.这也应该是有效的,只需要产品数组的一次迭代。

We'd run the reduce over both arrays, ensuring that we'll end up with a productCount of zero where no products for that category exist.我们将在 arrays 上运行 reduce,确保在该类别不存在任何产品的情况下,我们最终将 productCount 为零。

 const products = [ { brand: 'Levis', category: 'Jeans', }, { brand: 'Levis', category: 'Jeans', }, { brand: 'Levis', category: 'Tees', }, ]; const categories = [ { name: 'Jeans', }, { name: 'Tees', }, { name: 'Foo', } ]; const result = Object.values([...categories,...products].reduce((acc, { brand, category, name }) => { const key = name || category; acc[key] = acc[key] || { name: key, productCount: 0 }; if (category) acc[key].productCount++; return acc; }, {})); console.log('Result:', result);
 .as-console-wrapper { max-height: 100%;important }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试遍历对象数组以使用对象中的数据填充数组 - Trying to loop through an array of objects to populate arrays with data in objects 如何遍历数组并从Angular 5数据库中获取一些数据 - How to loop through an array, and get some data from database Angular 5 如何使用数组/对象遍历数组并在Angular中为属性分配新值? - How to loop through array with arrays/objects and assign properties new values in Angular? 从 JSON 数据中循环遍历第一个数组中的多个对象,显示两个 arrays 与使用 FUNCTION 组件的 React 中的对象 - loop through multiple objects inside the first array from JSON data displaying two arrays with objects in React using FUNCTION COMPONENT 循环遍历对象数组,以在嵌套数组中提取数据 - Loop through array of objects, to extract data within nested arrays 如何遍历两个具有多个 arrays 内部的对象以获得我想要的值? - How do I loop through two objects with multiple arrays inside to get the values I want? 如何遍历对象数组和数组的嵌套数组 - how to loop through array of objects and separate nested array of arrays 如何将一些数据减少到一个新的对象数组中? - How to reduce some data into a new array of objects? JavaScript遍历两个数组并获得单个数组 - JavaScript loop through two arrays and get single array 循环遍历对象 Javascript 的两个 arrays - Loop through two arrays of objects Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM