[英]How to get value from specify key in JSON
I have this objects: 我有这个对象:
{label: "Name1", values: ["el0", "el1"]}
{label: "Name2", values: ["el0", "el1"]}
I need to catch label
values from this object and values
array. 我需要从此对象和
values
数组中捕获label
值。 So i do this: 所以我这样做:
$.each(obj, function(index, value){
if (index === "label"){
var labels = value;
}
// actions with data here
});
If i do my actions outside of if labels var is undefined
, can anybody help? 如果我在标签var
undefined
,有人可以帮忙吗?
If you're trying to access a property on an object, you don't need the if statement. 如果尝试访问对象的属性,则不需要if语句。
objects.forEach(function(object){
var label = object.label;
//do stuff with label
});
With regards to your posted code, index
will always return an integer value, so it will never equal "label"
, and labels
will never be given a value. 关于您发布的代码,
index
将始终返回整数值,因此它将永远不等于"label"
,并且labels
将永远不会被赋值。 Javascript scopes things according to functions, so the variable labels
is accessible anywhere in the callback of the each
method. Javascript根据函数对事物进行范围划分,因此可以在
each
方法的回调中的任何位置访问变量labels
。
It's even accessible before it's defined, due to variable hoisting, though the value is undefined. 尽管变量值未定义,但由于变量提升,它甚至可以在定义之前访问。
try this: 尝试这个:
var labels = null;
$.each(obj, function(index, value){
if (index === "label"){
labels = value;
}
// actions with data here
// now you can use "labels" variable anywhere,
// because it has a global scope.
});
you need array.push
for this i guess 我猜你需要
array.push
var labels = [];
for (var i in obj)
labels.push(obj[i].label);
console.log(labels);
insted use $.each, try access the label attribute directly. 插入$ .each,尝试直接访问label属性。
var labels = obj['label'];
or 要么
var labels = obj.label;
If what you have is an array. 如果您有一个数组。 try this.
尝试这个。
var labels =[];
$.each(objs, function(i, item){
labels.push(item.label);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.