javascript 访问对象数组中的对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19154224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:35:00  来源:igfitidea点击:

Access object property in array of objects

javascriptarrays

提问by A Super Awesome

I have this set

我有这一套

var data = [
    {"outlet_name":"Easy Lane Supermart","20130102_20130108":"0"},
    {"outlet_name":"Eunilaine Foodmart Kalayaan","20130102_20130108":"0"},
    {"outlet_name":"PUREGOLD PRICE CLUB, INC - VISAYAS","20130102_20130108":"0"}
];

$.each(data, function (i, item) {
    $.each(item, function (k,v) {
        $('#result').append(k,v);
    });
});

How can I make it only view all the values of outlet_namewithout using the item.outlet_name?

我怎样才能让它只查看所有的值outlet_name而不使用 item.outlet_name?

回答by Strille

$.each(data, function (i, item) {
    console.log(item.outlet_name);
});

Or without jQuery:

或者没有 jQuery:

for (var i=0;i<data.length;i+=1) {
    console.log(data[i].outlet_name);
}

Ok, if you want to iterate over each object you can write:

好的,如果你想遍历每个对象,你可以写:

$.each(data, function (i, item) {
    console.log("Values in object " + i + ":");
    $.each(item, function(key, value) {
        console.log(key + " = " + value);
    });
});

回答by VIJAYABAL DHANAPAL

This will provide exact answer...

这将提供准确的答案...

var data = [
    {"outlet_name":"Easy Lane Supermart","20130102_20130108":"0"},
    {"outlet_name":"Eunilaine Foodmart Kalayaan","20130102_20130108":"0"},
    {"outlet_name":"PUREGOLD PRICE CLUB, INC - VISAYAS","20130102_20130108":"0"}
];
for(i=0;i<data.length;i++){
 for(var x in data[i]){
     console.log(x + " => " + data[i][x]);
 }
}

回答by Leonardo Wildt

If anyone is needing to do this from a JSON string for example

例如,如果有人需要从 JSON 字符串执行此操作

var myJson = [{"Code":"slide_1.png","Description":"slide_1"},{"Code":"slide_2.png","Description":"slide_2"},{"Code":"slide_3.png","Description":"slide_3"}]

You can use var newJsonArray = JSON.Parse(myJson)and you will get Array[3] 0 : Object 1 : Object 2 : Object

你可以使用 var newJsonArray = JSON.Parse(myJson),你会得到 Array[3] 0 : Object 1 : Object 2 : Object

At which point you can access it by simply saying newJsonArray[i].Codeor whatever property inside the array you want to use. Hope this helps!

在这一点上,您可以通过简单地说出newJsonArray[i].Code或您想要使用的数组中的任何属性来访问它。希望这可以帮助!