I'm trying to do an object manipulation in javascript, but it's not working as expected.
The code is this:
let data = [{
"Code": "COD01",
"Size Options": "85-90-95-100",
}, {
"Code": "COD02",
"Size Options": "85-90-95-100",
}];
let newData = [];
data.forEach(function(product) {
newData.push(product);
if (product["Size Options"].indexOf('-') > -1) {
let variations = product["Size Options"].split('-');
let prodVariation = product;
variations .forEach(function(variation) {
prodVariation["Code"] = prodVariation["Code"] + '-' + variation;
newData.push(prodVariation);
console.log(prodVariation);
});
}
});
console.log('New data:');
console.log(JSON.stringify(newData, null, 4));
The intention was to look like this in the newData
variable:
[
{
"Code": "COD01",
"Size Options": "85-90-95-100"
},
{
"Code": "COD01-85",
"Size Options": "85-90-95-100"
},
{
"Code": "COD01-90",
"Size Options": "85-90-95-100"
},
{
"Code": "COD01-95",
"Size Options": "85-90-95-100"
},
{
"Code": "COD01-100",
"Size Options": "85-90-95-100"
},
{
"Code": "COD02",
"Size Options": "85-90-95-100"
},
{
"Code": "COD02-85",
"Size Options": "85-90-95-100"
},
{
"Code": "COD02-90",
"Size Options": "85-90-95-100"
},
{
"Code": "COD02-95",
"Size Options": "85-90-95-100"
},
{
"Code": "COD02-100",
"Size Options": "85-90-95-100"
}
]
But it's looking like this:
[
{
"Code": "COD01-85-90-95-100",
"Size Options": "85-90-95-100"
},
{
"Code": "COD01-85-90-95-100",
"Size Options": "85-90-95-100"
},
{
"Code": "COD01-85-90-95-100",
"Size Options": "85-90-95-100"
},
{
"Code": "COD01-85-90-95-100",
"Size Options": "85-90-95-100"
},
{
"Code": "COD01-85-90-95-100",
"Size Options": "85-90-95-100"
},
{
"Code": "COD02-85-90-95-100",
"Size Options": "85-90-95-100"
},
{
"Code": "COD02-85-90-95-100",
"Size Options": "85-90-95-100"
},
{
"Code": "COD02-85-90-95-100",
"Size Options": "85-90-95-100"
},
{
"Code": "COD02-85-90-95-100",
"Size Options": "85-90-95-100"
},
{
"Code": "COD02-85-90-95-100",
"Size Options": "85-90-95-100"
}
]
I've tried to solve the problem in several ways, both with jQuery and Javascript. I also tried copying the object, because it seems that it is making the change on top of another change, instead of taking the base object, but I couldn't solve it. Can anyone help me with this?