2

I have this object from a JSON file

{
    "Apple": "Red",
    "Orange": "Orange",
    "Guava": "Green",   
}

Then I converted it into Object using

var data = JSON.parse(dataFromJson);

then it will output JavaScript object

Question

Is it possible to access "Apple", "Orange", "Guava" then store it into var fruits then "Red", "Orange","Green" into var Color

2 Answers 2

3

You can also do something like this:

var data = JSON.parse(dataFromJson);

var fruits = [];
var colors = [];

for(var fruit in data) {
    fruits.push(fruit);
    colors.push(data[fruit]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This associating is more elegant than mine :) thumbs up for that, have an upvote
1

Yes, there is several ways to do this, either iterate over the object and do it "manually"

for (var i = 0;i > data.length; i++) {
    colors.push(data[i]);
    fruits.push(Object.keys(data)[i]);
}

or let the Object methods do this for you.

var fruits = Object.keys(data);
var colors = Object.values(data);

Have some reading about the Object here

The Object.values() method is EXPERIMENTAL as stated here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.