How to split nested Object into Array of Objects - avoiding for loop

Viewed 665

I want to split a nested Object into an Array of Objects. I am able to achieve the same using two FOR Loops.

Is there any way I can have a better solution, or this is correct?

Below snippet for reference.

 var Input = {
      "English": {
        "v1": "10",
        "v2": "11",
        "v3": "34"
      },
      "Hindi": {
        "v1": "14",
        "v2": "16",
        "v3": "18"
      }
    }
    var Output = []

 for (let i = 0; i < Object.keys(Input).length; i++) {
      for (let j = 0; j<Object.keys(Object.values(Input)[i]).length; j++) {
        Output.push({
          "parameter": Object.keys(Input)[i],
          "machine": Object.keys(Object.values(Input)[i])[j],
          "value":Object.values(Object.values(Input)[i])[j]
        })
      }
    }


console.log(Output)

1 Answers

You could use Object.entries() and Array.flatMap():

var Input = {
  English: {
    v1: "10",
    v2: "11",
    v3: "34",
  },
  Hindi: {
    v1: "14",
    v2: "16",
    v3: "18",
  },
};

const Output = Object.entries(Input).flatMap(([parameter, values]) =>
  Object.entries(values).map(([machine, value]) => ({
    parameter,
    machine,
    value,
  }))
);

console.log(Output);

Here the .flatMap() flattens the arrays created by the Object.entries().map() into one big array. It also uses array destructuring to pick out the key and value from the tuple which Object.entries() produces.

Related