0

I have data of json as sample

[{"Food":"Orange T1","Total":3},
{"Food":"Blue T2","Total":1},
{"Food":"Green T3","Total":1},
{"Food":"White T4","Total":4}]

and i want to convert to array object as

[['Orange T1', 3], ['Blue T2', 1], ['Green T3', 1],['White T4', 4]]

How I do this and I will use console.log() to show data sample.

3
  • do you have an array or a JSON string? Commented Mar 22, 2018 at 16:26
  • .map({food, total} => [food, total]) should do the trick Commented Mar 22, 2018 at 16:27
  • I have a data of json Commented Mar 22, 2018 at 16:28

2 Answers 2

4

You could map the values of each object.

var array = [{ Food: "Orange T1", Total: 3 }, { Food: "Blue T2", Total: 1 }, { Food: "Green T3", Total: 1 }, { Food: "White T4", Total: 4 }],
    result = array.map(Object.values);
    
console.log(result);

If you do not rely on insertation order of objects values, you could use explit keys and their values.

ES6

var array = [{ Food: "Orange T1", Total: 3 }, { Food: "Blue T2", Total: 1 }, { Food: "Green T3", Total: 1 }, { Food: "White T4", Total: 4 }],
    result = array.map(({ Food, Total }) => [Food, Total]);
    
console.log(result);

ES5

var array = [{ Food: "Orange T1", Total: 3 }, { Food: "Blue T2", Total: 1 }, { Food: "Green T3", Total: 1 }, { Food: "White T4", Total: 4 }],
    result = array.map(function (o) { return [o.Food, o.Total]; });
    
console.log(result);

Sign up to request clarification or add additional context in comments.

5 Comments

As the order of properties is unordered, this might not work everywhere.
the order is usually the insertation order, as long as the object does not have keys which could be read as integer. these values are listed first.
Usually yes, but not necessarily according to the specification.
Dear Nina Scholz, with case result = array.map(({ Food, Total }) => [Food, Total]); . It's not working , Are you sure for this ?
@BrianCrist, it is ES6 syntax, i add ES5.
1
var newArr = JSON.parse(yourJson).map((item) => {return [item.Food, item.Total]})

console.log(newArr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.