首页 > 解决方案 > Lodash 合并两个数组并对其进行分类

问题描述

我需要合并两个数组:类别和产品。每个产品都有一个类别对象。我需要按类别组织,包括类别对象并保留空类别。GroupBy 函数只包含一个参数。

const Categories= [   
  {id: 1, 'name': 'category1'}
  {id: 2, 'name': 'category2'},
  {id: 3, 'name': 'category3'},
  {id: 4, 'name': 'category4'},    
]
const Products= [   
  {id: 1, 'name': 'product1', category: {id: 1, name: 'category1'}},
  {id: 2, 'name': 'product2', category: {id: 1, name: 'category1'}},
  {id: 3, 'name': 'product3', category: {id: 2, name: 'category2'}},
  {id: 4, 'name': 'product4', category: {id: 2, name: 'category2'}},    
]

预期结果

const result = [
  {
    category: {id: 1, name: 'category1'}, 
    products:[{id:1, name: 'produt1'}, {id: 2, name: 'produto1'} ]
  },
  {
    category: {id: 2, name: 'category2'}, 
    products:[{id:3, name: 'produt3'}, {id: 4, name: 'produto4'} ]
  },
  {
    category: {id: 3, name: 'category3'}, 
    products:[]
  },
 {
    category: {id: 4, name: 'category4'}, 
    products:[]
  },
]

尝试:

 for (i = 0; i < categoriesJson.length; i++) {
            categoriesJson[i] =   _.assign({}, categoriesJson[i], { products: [] })
            for (j = 0; j < productsJson.length; j++) {
                if(productsJson[j].categoryId.objectId === categoriesJson[i].objectId){
                    categoriesJson[i].products.push(productsJson[j])
                }
            }
        }

标签: javascriptarraysmergelodash

解决方案


如果解决方案中不需要 lodash,这就是我使用纯 javascript 的方式;

const Categories= [   
  {id: 1, 'name': 'category1'},
  {id: 2, 'name': 'category2'},
  {id: 3, 'name': 'category3'},
  {id: 4, 'name': 'category4'}    
];

const Products= [   
  {id: 1, 'name': 'product1', category: {id: 1, name: 'category1'}},
  {id: 2, 'name': 'product2', category: {id: 1, name: 'category1'}},
  {id: 3, 'name': 'product3', category: {id: 2, name: 'category2'}},
  {id: 4, 'name': 'product4', category: {id: 2, name: 'category2'}},    
];

const result = [];

for (let index in Categories) {
  let category_id = Categories[index].id;
  result.push({
    category: Categories[index],
    products: GetProductsWithCategoryId(category_id)
  }); 
}

function GetProductsWithCategoryId(category_id) {
  let products = [];
  for (let index in Products) {
    if (Products[index].category.id == category_id) {
      products.push({
        id: Products[index].id,
        name: Products[index].name
      });
    }
  }
  return products;
}

console.log("result:", result);


推荐阅读