How to split and merge javascript object with respect to index of array attribute.
I have fields like that.
var myFields = {
Country: "USA",
State: "DC",
Cataogry: ["Value1", "Value2"],
Level: ["Level1", "Level2"]
};
I want to derive two from here like this. Output : -
var fields = [
{ Country: "USA", State: "DC", Cataogry: "Value1", Level: "Level1" },
{ Country: "USA", State: "DC", Cataogry: "Value2", Level: "Level2" }
];
So When I am using my code I am getting 4 arrays instead of two. Can anybody help me with how to merge with respect to the index.
Here is what I have tried:
var myObj = {};
for (var i = 0; i < fields.length; i++) {
myObj[fields[i].key] = fields[i].Value;
}
var myObjList = [];
var listFlag = false;
Object.keys(myObj).forEach(function(key) {
if (Array.isArray(myObj[key])) {
listFlag = true;
myObj[key].forEach(function(el) {
var objCopy = JSON.parse(JSON.stringify(myObj));
objCopy[key] = el;
myObjList.push(objCopy);
});
}
});
if (!listFlag) {
myObjList.push(myObj);
}