I want to handle the array according to number of properties for a category.
I have created an array(array_a) using available properties, and I group that array value according to properties(array_colors,array_sizes). for example now i have two arrays 'array_colors' and 'array_sizes', so in my code I for loop them and created an object array(array_b). but my issue is I want to handle dynamic number of properties.
var array_a = [
{
"color":{
"id":2,
"name":"Green"
}
},
{
"color":{
"id":3,
"name":"Yellow"
}
},
{
"size":{
"id":5,
"name":"16"
}
},
{
"size":{
"id":6,
"name":"17"
}
},
{
"size":{
"id":7,
"name":"18"
}
}
];
array_colors = array_a.filter(function(myObject) {
return myObject.hasOwnProperty('color');
});
array_sizes = array_a.filter(function(myObject) {
return myObject.hasOwnProperty('size');
});
array_b = [];
for(var i = 0; i < array_colors.length; i++) {
for (var j = 0; j < array_sizes.length; j++) {
array_b.push( {
"is_available":true,
"qty":0,
"price":0,
"color":array_colors[i],
"size":array_sizes[j]
});
}
}
array_b = [
{
"is_available":true,
"qty":0,
"price":0,
"color":{
"id":2,
"name":"Green"
},
"size":{
"id":5,
"name":"16",
"text":"16"
}
},
{
"is_available":true,
"qty":0,
"price":0,
"color":{
"id":2,
"name":"Green"
},
"size":{
"id":6,
"name":"17",
"text":"17"
}
},
{
"is_available":true,
"qty":0,
"price":0,
"color":{
"id":2,
"name":"Green"
},
"size":{
"id":7,
"name":"18",
"text":"18"
}
},
{
"is_available":true,
"qty":0,
"price":0,
"color":{
"id":3,
"name":"Yellow"
},
"size":{
"id":5,
"name":"16",
"text":"16"
}
},
{
"is_available":true,
"qty":0,
"price":0,
"color":{
"id":3,
"name":"Yellow"
},
"size":{
"id":6,
"name":"17",
"text":"17"
}
},
{
"is_available":true,
"qty":0,
"price":0,
"color":{
"id":3,
"name":"Yellow"
},
"size":{
"id":7,
"name":"18",
"text":"18"
}
}
]
my expected array as above.I want to handle the properties such as color,size dynamically.
using _.mergeWith()
you can merge the properties to a single object with the property names as the keys, and an array of values for each key. Then reduce the object to an array of objects using _.flatMap()
(or Array.flatMap()
:
const array_a = [{"color":{"id":2,"name":"Green"}},{"color":{"id":3,"name":"Yellow"}},{"size":{"id":5,"name":"16"}},{"size":{"id":6,"name":"17"}},{"size":{"id":7,"name":"18"}}]; const getAllCombinations = _.flow([ arr => _.mergeWith({}, ...arr, (o, s) => _.isArray(o) ? [...o, s.name] : [s.name]), props => _.reduce(props, (r, values, k) => _.isEmpty(r) ? values.map(v => ({ is_available: true, qty: 0, price: 0, [k]: v, })) : _.flatMap(r, o => values.map(v => ({ ...o, [k]: v }))), []) ]); console.log(getAllCombinations(array_a));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.