I saw many similar questions like this. But none of them helped me to fulfill my need. So I'm posting this question.
I have multiple arrays as per the users' choice. As an example, I will use 2 arrays here.
color = [{id: 1, name: "Red"}, {id: 2, name: "Green"}, {id: 1, name: "Blue"}]
size = [{id: 1, name: "Small"}, {id: 2, name: "Medium"}]
I want to get all possible combinations of given arrays and add some keys on top of that as an output.
My expected output is something like the below.
[{"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}]
If the user gives 3 arrays then it should create the combination accordingly but the properties "price"
and "Quantity"
will be added to the combination.
Please suggest to me how can I achieve this in Angular?
CodePudding user response:
Just go through the lists and build the objects:
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)
If you have an arbitrary number of arrays, you need to find a way to specify keys for it, for example by putting them into an 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, 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)