简体   繁体   中英

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. Obviously, idx itself is not a member of the object, but it contains the member name. How do I use idx to access 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] ;

You can access a property on an object in JavaScript like obj.prop or obj["prop"] or obj[idx] where idx === "prop" .

In 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. 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");
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM