I am trying to use an javascript algorithm to convert the data from products mode to reward mode, please help me :
var products = [{
id: "65864",name_fa:"پک دفتر 40 برگ وزيري شوميز کلاسيک 40 ",
details:[{master: 5,slave: 0,slave2: 0},{master: 11,slave: 0,slave2: 0}]
},{
id: 67532,name_fa: "100-بازی لونا",
details:[{master: 0,slave: 5,slave2: 0}]
}]
TO :
reward: [
{products: [
{
id: "65864",
name_fa:"پک دفتر 40 برگ وزيري شوميز کلاسيک 40" ,
"master": "5",
"slave": "0",
"slave2": "0"
},
{
"id": "67532",
"name_fa":"100-بازی لونا" ,
"master": "0",
"slave": "5",
"slave2": "0"
}
],
},
{"products": [
{
"id": "65864",
"name_fa":"پک دفتر 40 برگ وزيري شوميز کلاسيک 40" ,
"master": "11",
"slave": "0",
"slave2": "0"
},
{
"id": "67532",
"name_fa":"100-بازی لونا" ,
"master": "0",
"slave": "5",
"slave2": "0"
}
],
}
]
example:
[1,2],[3]
to
[1,3],[2,3]
I am trying to use an javascript algorithm to convert the data from products mode to reward mode, please help me
CodePudding user response:
It's called cartesian product. I'm reusing a function and apply it on 2 arrays. The products, and the details. Then I combine those arrays (should be same length) into the required result.
// from: https://stackoverflow.com/a/36234242/3807365
function cartesianProduct(arr) {
return arr.reduce(function(a, b) {
return a.map(function(x) {
return b.map(function(y) {
return x.concat([y]);
})
}).reduce(function(a, b) {
return a.concat(b)
}, [])
}, [
[]
])
}
var products = [{
id: "65864",
name_fa: "پک دفتر 40 برگ وزيري شوميز کلاسيک 40 ",
details: [{
master: 5,
slave: 0,
slave2: 0
}, {
master: 11,
slave: 0,
slave2: 0
}]
}, {
id: 67532,
name_fa: "100-بازی لونا",
details: [{
master: 0,
slave: 5,
slave2: 0
}]
}];
var input = products.reduce(function(agg, item) {
agg.push(item.details);
return agg;
}, []);
var a = cartesianProduct(input);
// same for the id and names
var input2 = products.reduce(function(agg, item) {
var ids = []
item.details.forEach(function(_) {
ids.push({
id: item.id,
name_fa: item.name_fa
})
})
agg.push(ids);
return agg;
}, []);
var b = cartesianProduct(input2);
//console.log(JSON.stringify(a, null, 2));
//console.log(b)
var reward = [];
for (var i = 0; i < a.length; i ) {
var newGroup = {
products: []
}
for (var j = 0; j < a[i].length; j ) {
var newMan = {}
newGroup.products.push({
...b[i][j],
...a[i][j]
})
}
reward.push(newGroup)
}
console.log(reward)
.as-console-wrapper {
max-height: 100% !important
}