PSR PSR - 2 months ago 14
Javascript Question

Convert object to another object using jQuery

I am getting a result in my JavaScript file which I want to convert into another object.

My original result

[
{
"SName": "Set1",
"Elements": [
{
"Id": "3",
"Name": "Name1"
},
{
"Id": "5",
"Name": "Name2"
}
]
},
{
"SName": "Set2",
"Elements": [
{
"Id": "7",
"Name": "Name3"
},
{
"Id": "8",
"Name": "Name4"
}
]
}
]


Convert this to look like array of objects using jQuery or JavaScript. How can I achieve this?

[
{
"SName": "Set1",
"Id": 3,
"Name": "Name1"
},
{
"SName": "Set1",
"Id": 5,
"Name": "Name2"
},
{
"SName": "Set2",
"Id": 7,
"Name": "Name3"
},
{
"SName": "Set2",
"Id": 8,
"Name": "Name4"
}
]

Answer
var data =     [
  {
    "SName": "Set1",
    "Elements": [
      {
        "Id": "3",
        "Name": "Name1"
      },
      {
        "Id": "5",
        "Name": "Name2"
      }
    ]
  },
  {
    "SName": "Set2",
    "Elements": [
      {
        "Id": "7",
        "Name": "Name3"
      },
      {
        "Id": "8",
        "Name": "Name4"
      }
    ]
  }
];
console.log(data);

var newData = data.reduce(function (newArray, currentSet) {
    return newArray.concat(currentSet.Elements.map(function (element) {
        return Object.assign( { SName: currentSet.SName }, element);
    }));
}, []);

console.log(newData);

The key here is the reduce function. What we are doing is creating a brand new array, by looping through each value of the outer array. We continuously concatenate onto our new array with the values we map from the inner array.

Comments