[英]Create new array depending of the number of properties in another object in Javascript
[英]Create object array according to changing number of properties
我想根據類別的屬性數量處理數組。
我使用可用屬性創建了一個數組(array_a),並根據屬性(array_colors,array_sizes)對該數組值進行分組。 例如,現在我有兩個數組“array_colors”和“array_sizes”,所以在我的代碼中我循環它們並創建了一個對象數組(array_b)。 但我的問題是我想處理動態數量的屬性。
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"
}
}
]
我預期的數組如上。我想動態處理顏色、大小等屬性。
使用_.mergeWith()
您可以將屬性合並為一個對象,以屬性名稱作為鍵,以及每個鍵的值數組。 然后使用_.flatMap()
(或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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.