【问题标题】:Combine multiple arrays and convert it to another object array in Angular合并多个数组并将其转换为 Angular 中的另一个对象数组
【发布时间】:2023-01-26 19:12:11
【问题描述】:

我看到很多类似的问题。但他们都没有帮助我满足我的需要。所以我发布了这个问题。

根据用户的选择,我有多个阵列。作为示例,我将在这里使用 2 个数组。

color = [{id: 1, name: "Red"}, {id: 2, name: "Green"}, {id: 1, name: "Blue"}]
size = [{id: 1, name: "Small"}, {id: 2, name: "Medium"}]

我想获得给定数组的所有可能组合,并在其上添加一些键作为输出。

我的预期输出如下所示。

[{"color": "Red", "size": "Small", "price":0, "Quantity": 0},
{"color": "Red", "size": "Medium", "price":0, "Quantity": 0},
{"color": "Green", "size": "Small", "price":0, "Quantity": 0},
{"color": "Green", "size": "Medium", "price":0, "Quantity": 0},
{"color": "Blue", "size": "Small", "price":0, "Quantity": 0},
{"color": "Blue", "size": "Medium", "price":0, "Quantity": 0}]

如果用户提供 3 个数组,那么它应该相应地创建组合,但是属性 "price""Quantity" 将被添加到组合中。

请向我建议如何在 Angular 中实现这一点?

【问题讨论】:

  • pricequantity 来自哪里?
  • 如果用户给出 3 个数组,但您只向我们展示了 2 个数组。第三阵是?

标签: javascript arrays angular combinations


【解决方案1】:

只需浏览列表并构建对象:

const colors = [{id: 1, name: "Red"}, {id: 2, name: "Green"}, {id: 1, name: "Blue"}]
const sizes = [{id: 1, name: "Small"}, {id: 2, name: "Medium"}]

const otherProps = {price:0, Quantity: 0}
const res = colors.flatMap(color => sizes.map(size => ({color: color.name, size: size.name, ...otherProps})))
console.log(res)

如果你有任意数量的数组,你需要找到一种方法来为它指定键,例如将它们放入一个对象中:

const data = {
  color: [{id: 1, name: "Red"}, {id: 2, name: "Green"}, {id: 1, name: "Blue"}],
  sizes: [{id: 1, name: "Small"}, {id: 2, name: "Medium"}],
  stuff: [{name: 'foo'}, {name: 'bar'}]
}
const otherProps = {price:0, Quantity: 0}

const result = Object.entries(data)
  .map( ([propName, values]) => values.map(v =>({[propName]: v.name})))  // build the key-value pairs, i.e. [{color: 'Red'}, ...] 
  .reduce( (groups, props) => groups.length === 0 ? props : 
    groups.flatMap(group => props.map(prop => ({...group, ...prop, ...otherProps})))  // add new properties to existing groups
  );

console.log(result)

【讨论】:

    【解决方案2】:

    您尝试实现的概念是数据库中所谓的 CROSS JOIN。

    关键概念是您必须迭代两个数组。

    你可以通过.reduce()实现

    let result: any[] = color.reduce((acc: any[], cur: any) => {
        for (let s of size) {
            acc.push({
                color: cur.name,
                size: s.name,
                price: 0,
                Quantity: 0
            });
        }
    
        return acc;
    }, []);
    

    或者使用 .forEach() 或什至是简单的 for 循环。

    let result2: any[] = [];
    color.forEach(x => {    
        for (let s of size) {
            result2.push({
                color: x.name,
                size: s.name,
                price: 0,
                Quantity: 0
            });
        }
    });
    

    Demo @ TypeScript Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2022-11-08
      • 1970-01-01
      相关资源
      最近更新 更多