By Nazem Mahmud


2018-09-14 15:02:37 8 Comments

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 ?

7 comments

@ksav 2018-09-14 15:14:18

If we weren't using jQuery, we could use a combination of Object.keys() and Array.prototype.map()

Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop.

Object.keys(data) would simply return ["A", "B", "C", "D"]


The map() method creates a new array with the results of calling a provided function on every element in the calling array.

In that map function callback we can return an object in the specific way we need our data formatted.

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

const newData = Object.keys(data).map(function(prop) {
  return {
    name: prop,
    data: data[prop]
  }
})

console.log(newData)

@Nazem Mahmud 2018-09-14 17:39:26

Thanks for your idea :)

@user633183 2018-09-14 15:09:13

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

@Grégory NEUT 2018-09-14 15:13:27

Like it with destructuration, well thought. Be carefull tho about the support of the Object.entries method in browser check here

@Bendy Zhang 2018-09-14 15:14:57

The following code will return your expected result.

var newData = [];
for(var key in data) {
    newData.push({
        name: key,
        data: data[key]
    });
}

@filippo 2018-09-14 15:08:48

Should be:

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

You also don't need to use jQuery. You can do the same in vanilla JS:

var newData = [];
Object.keys(data).forEach(function(k) {
    newData.push({'name': k, 'data': data[k]});
});

@Nazem Mahmud 2018-09-14 17:39:01

Thank you for your suggestion :)

@Emeeus 2018-09-14 15:08:08

You could use a for in loop and push each element.

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

var newArr = [];

  for(p in obj){
    newArr.push({"name":p,"data":obj[p]})
  }

  console.log(newArr)

@Nazem Mahmud 2018-09-14 15:29:33

Thanks for your suggestion :)

@Grégory NEUT 2018-09-14 15:06:30

You can use of Object.keys and Array.map to generate your array.

It can be translated to :

for each key in my object data, create a new item inside of a new array. This item gonna be an object, with a key name and a key data.


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

const ret = Object.keys(data).map(x => ({
  name: x,
  data: data[x],
}));

console.log(ret);

@Guy who types fast 2018-09-14 15:06:14

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

@Nazem Mahmud 2018-09-14 15:28:57

Thanks. It Works :)

Related Questions

Sponsored Content

25 Answered Questions

41 Answered Questions

[SOLVED] How do I check if an array includes an object in JavaScript?

88 Answered Questions

[SOLVED] How do JavaScript closures work?

36 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

28 Answered Questions

[SOLVED] For-each over an array in JavaScript?

69 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5016178 View
  • 6304 Score
  • 69 Answer
  • Tags:   javascript arrays

63 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

53 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

48 Answered Questions

Sponsored Content