0

The array of objects looks like this:

[
    {"Number":64,"Earning":160000},{"Number":64,"Earning":160000},
    {"Number":64,"Earning":160000},{"Number":64,"Earning":160000},
    {"Number":64,"Earning":160000},{"Number":64,"Earning":160000},
    {"Number":64,"Earning":160000},{"Number":64,"Earning":160000}
]

and the required JavaScript array is:

[
    [160000, 64], [160000, 64], [160000, 64], [160000, 64],
    [160000, 64], [160000, 64], [160000, 64], [160000, 64]
]

I want to convert JSON object data into JavaScipt and JSON data which I supply is given above and JavaScript array which I want is also defined. I want a JavaScript methode which solves this problem

2

3 Answers 3

3

If you're using this exact structure, you can do something like this. Where inputData is the first JSON structure, and outputData will be the data outputted.

var outputData = [];

for(var i = 0; i < inputData.length; i++) {
    var input = inputData[i];

    outputData.push([input.Earning, input.Number]);
}
Sign up to request clarification or add additional context in comments.

10 Comments

Good, but I would suggest outputData[i] = [...] instead of using .push(), just to save a function call ;)
Meh, micro-optimizations, but good point. I just like it for the cleanliness per say.
I know, I know, I'm a nut like that XD But if I know the index number already I just like to make use of it.
@Kolink: how about var outputData = new Array(inputData.length); then?
@Kolink: but then you would have a single allocation
|
0

Iterate over the array and construct a new array. Most javascript libraries have a map function where you only need to supply a mapping function to achieve this.

Comments

0

This Way (Works only in modern browsers):

var a = [
    {"Number":64,"Earning":160000},{"Number":64,"Earning":160000},
    {"Number":64,"Earning":160000},{"Number":64,"Earning":160000},
    {"Number":64,"Earning":160000},{"Number":64,"Earning":160000},
    {"Number":64,"Earning":160000},{"Number":64,"Earning":160000}
];

var b = a.map(function(i) {  return [i.Earning,i.Number];  });   // New Array

5 Comments

And where is the result? forEach does not modify the original array.
Really? It seems to modify the original array as well... when I checked in my console.
Somehow you must have checked it wrong ;) developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Really sorry about the mistake. I did use map in console... which gave me the other result.
.map returns the new array though, so you have to assign the result to a variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.