1

I have one json file with following structure:

{
    "won":3,
    "lost":0,
    "void":0,
    "active":1
}

I've been trying to figure out how to make two arrays in javascript that will contain following information:

var labels = ["won", "lost", "void", "active"];
var data = ["3","0", "0","1"];

But I can't my head around how to do it.

4 Answers 4

4

You can use:

var labels = Object.keys(input);
var data = Object.values(input);

However you should check the browsers compatibility:

Object.keys Object.values

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

1 Comment

(Remember to parse the JSON first)
1

Try this code

var item_list = {
    "won":3,
    "lost":0,
    "void":0,
    "active":1
};

var labels = [];
var data = [];
for(var item in item_list){
 // console.log(item);
  labels.push(item);
  data.push(item_list[item]);
}

console.log(labels);
console.log(data);

Comments

0

You can do this too

var mydata = {
    "won":3,
    "lost":0,
    "void":0,
    "active":1
};

var first = [],
    second = [];

for (var property in mydata) {

   if ( ! mydata.hasOwnProperty(property)) {
      continue;
   }

   first.push(property);
   second.push(mydata[property]);

}

console.log(first);
console.log(second);

Comments

0

Try This :

var obj = {
    "won":3,
    "lost":0,
    "void":0,
    "active":1
}
var keys = new Array();
var values = new Array();

for (var key in obj) {
  keys.push(key)
  values.push(obj[key]);
}

console.log(keys);
console.log(values);

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.