I have this object from a JSON
file
我从JSON文件中获取此对象
{
"Apple": "Red",
"Orange": "Orange",
"Guava": "Green",
}
Then I converted it into Object
using
然后我用它将它转换为Object
var data = JSON.parse(dataFromJson);
then it will output JavaScript object
然后它将输出JavaScript对象
Question
题
Is it possible to access "Apple", "Orange", "Guava"
then store it into var fruits
then "Red", "Orange","Green"
into var Color
是否可以访问“Apple”,“Orange”,“Guava”然后将其存储到var fruits中,然后将“Red”,“Orange”,“Green”存入var颜色
2 个解决方案
#1
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]);
}
#2
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.
或让Object方法为您执行此操作。
var fruits = Object.keys(data);
var colors = Object.values(data);
Have some reading about the Object here
在这里阅读一些关于Object的内容
The Object.values()
method is EXPERIMENTAL as stated here
Object.values()方法是如此处所述的实验
#1
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]);
}
#2
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.
或让Object方法为您执行此操作。
var fruits = Object.keys(data);
var colors = Object.values(data);
Have some reading about the Object here
在这里阅读一些关于Object的内容
The Object.values()
method is EXPERIMENTAL as stated here
Object.values()方法是如此处所述的实验