[英]Generic JSON Element Access
My colleague wrote a function to get all the keys out of a JSON object and check them against ones we're interested in. What I can't seem to search Google correctly for is how to take the variable holding the key name and use it to get the values. 我的同事编写了一个函数,用于从JSON对象中获取所有键,然后将它们与我们感兴趣的键进行比较。我似乎无法正确地在Google上进行搜索,这是如何获取包含键名的变量并使用它的获取值。 Obviously, idx itself is not a member of the object, but it contains the member name.
显然,idx本身不是对象的成员,但是包含成员名称。 How do I use idx to access obj?
如何使用idx访问obj?
$.each(JSON.parse(data[0][i]), function(idx, obj){
for(var j = 0; j < searchKeys.length; j++){
if (idx == searchKeys[j]) {
//How do I do this correctly?
injectLoc.innerHTML += panelMaker(obj.idx, idx, "green", "gears");
}
}
});
You can use it similar to how you'd access an element on an array. 您可以像访问数组元素一样使用它。
var value = obj[idx]
; var value = obj[idx]
;
You can access a property on an object in JavaScript like obj.prop
or obj["prop"]
or obj[idx]
where idx === "prop"
. 您可以使用
obj.prop
或obj["prop"]
或obj[idx]
其中idx === "prop"
在JavaScript中访问对象的属性。
In JSON, 在JSON中,
Accessing elements by index --> obj[idx]
Accessing values by keys --> obj.key or obj["key"]
Note: If key has spaces use only --> obj["key"]
You can use Object.keys() to iterate keys of the object. 您可以使用Object.keys()来迭代对象的键。 So the function could potentially work like this:
因此,该功能可能会像这样工作:
Object.keys(obj).forEach((key, index) => {
if(index === key){
injectLoc.innerHTML += panelMaker(obj[key], index, "green", "gears");
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.