简体   繁体   中英

How to iterate through a nested object in a JSON with nodejs?

I have this JSON:

{ 
    "USD" : {"15m" : 559.07, "last" : 559.07, "buy" : 559.07, "sell" : 562.39,  "symbol" : "$"},
    "CNY" : {"15m" : 3431.69912796, "last" : 3431.69912796, "buy" : 3431.69912796, "sell" : 3452.0780449199997,  "symbol" : "¥"}
}

Using nodejs, I've been trying to iterate through and return any of the members of the nested object. Assuming I wanted to get the member "last", I tried the following. However, I get "undefined". How should I access these members correctly?

        var bcData = JSON.parse(body);
        for (var key in bcData) {
            console.log(key + ": " + key.last + '\n');
        }

The object is still bcData. You need to first access key of bcData and then it's last property -

for (var key in bcData) {
    console.log(key + ": " + bcData[key].last + '\n');
}

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