How to split and merge javascript object with respect to index of array attribute

Viewed 280

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);
}
3 Answers

You could use map method.

var myFields = {
    "Country" : "USA",
    "State" : "DC",
    "Cataogry" : ["Value1","Value2"],
    "Level" : ["Level1","Level2"]
}

var fields = myFields.Cataogry.map((item, index) => ({
  Country : myFields.Country,
  State : myFields.State,
  Cataogry: myFields.Cataogry[index],
  Level : myFields.Level[index]
} ));

console.log(fields);

You can map it. Here is my try. I'm assuming category and level are of the same length.

var myFields = {
  Country: "USA",
  State: "DC",
  Cataogry: ["Value1", "Value2"],
  Level: ["Level1", "Level2"]
};

var result = myFields.Cataogry.map((Cataogry, i) => ({
  ...myFields,
  Cataogry,
  Level: myFields["Level"][i]
}));

console.log(result);

You could take a dynamic approach and iterate all entries and have a look to value.

If value is an array, map the values along with the object at the same index or take the first object as pattern.

If value is no array, map the accumulator and add the actual key/value pair to all objects.

var object = { Country: "USA", State: "DC", Category: ["Value1", "Value2"], Level: ["Level1", "Level2"] },
    result = Object
        .entries(object)
        .reduce(
            (r, [key, value]) => Array.isArray(value)
                ? value.map((v, i) => ({ ...(r[i] || r[0]), [key]: v }))
                : r.map(o => ({ ...o, [key]: value })),
            [{}]
        );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related