2

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 3

3

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);

Sign up to request clarification or add additional context in comments.

3 Comments

This solution is correct but I want to be generic one. I don't wantto use all the attributes. The way I have tried in my example.
Yes, but what is fields in your question ? Because you specified that fields is the output.
fields is a veriable where I am storing the value.
2

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; }

Comments

2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.