[英]Combine multiple arrays and convert it to another object array in Angular
我看到很多类似的问题。 但他们都没有帮助我满足我的需要。 所以我发布了这个问题。
根据用户的选择,我有多个 arrays。 作为示例,我将在这里使用 2 arrays。
color = [{id: 1, name: "Red"}, {id: 2, name: "Green"}, {id: 1, name: "Blue"}]
size = [{id: 1, name: "Small"}, {id: 2, name: "Medium"}]
我想获得给定 arrays 的所有可能组合,并在其上添加一些键作为 output。
我预期的 output 如下所示。
[{"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 arrays 那么它应该相应地创建组合,但是属性"price"
和"Quantity"
将被添加到组合中。
请向我建议如何在 Angular 中实现这一目标?
通过列表只需 go 并构建对象:
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)
如果你有任意数量的 arrays,你需要找到一种方法来为它指定键,例如将它们放入 object:
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, ie [{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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.