Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Convert object structure

I have an object like this:

{
  "A": [ "-4927","8779","-9971","-23767" ],
  "B": [ "-10617","-1456","3131","259" ],
  "C": [ "-5185","1168","21501","18989" ],
  "D": [ "2010","5664","2148","-674" ]
}

I want to convert to this:

[
  {
    name: 'A',
    data: ["-4927","8779","-9971","-23767"]
  }, {
    name: 'B',
    data: ["-10617","-1456","3131","259"]
  }, {
    name: 'C',
    data: ["-5185","1168","21501","18989"]
  }, {
    name: 'D',
    data: ["2010","5664","2148","-674"]
  }
]

I have used this following method:

var newData = [];
$.each($.parseJSON(data), function(k, v) {
  newData['name'] = k;
  newData['data'] = v;
});

But it only store the last key pair value as newData. That is

name: 'D',
data: ["2010","5664","2148","-674"]

I understand that it overwrite the previous data and store only the last data it get. But i can't solve this problem.

Any Help ?

like image 628
Nazem Mahmud Piash Avatar asked Sep 14 '18 15:09

Nazem Mahmud Piash


2 Answers

You are assigning the properties name and data directly to newData instead of pushing an object into it as an array:

Change your loop to this:

var newData = [];
$.each($.parseJSON(data), function(k, v) {
        const myNewData = {
            name: k,
            data: v
        }
        newData.push(myNewData);
});
like image 154
Guy who types fast Avatar answered Sep 24 '22 20:09

Guy who types fast


You can do this using map

const oldData =
  { "A": [ "-4927","8779","-9971","-23767" ]
  , "B": [ "-10617","-1456","3131","259" ]
  , "C": [ "-5185","1168","21501","18989" ]
  , "D": [ "2010","5664","2148","-674" ]
  }

const newShape = ([ name, data ]) =>
  ({ name, data })

const newData =
  Object.entries(oldData).map(newShape)

console.log(newData)
// [ { name: "A", data: [ "-4927","8779","-9971","-23767" ] }, ... ]

You can write the lambda inline, if you wish, but it's generally better to write programs with reusable pieces

const newData =
  Object.entries(oldData).map(([ name, data ]) => ({ name, data }))

jQuery can map over objects using $.map – note the differing lambda

const newData =
  $.map(oldData, (data, name) => ({ name, data }))
like image 28
Mulan Avatar answered Sep 25 '22 20:09

Mulan