Reputation: 182
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
Upvotes: 2
Views: 47
Reputation: 474
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
Upvotes: 1
Reputation: 333
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]);
}
Upvotes: 3