Home > Enterprise >  Getting values from json in JavaScript
Getting values from json in JavaScript

Time:06-02

If I have some json like this:

{
    "dcf93893d83e4f28953f140b9cba1963":{
       "foo":{
          "client":"127.0.0.1",
          "id":"31971",
          "start time":1654131724.160335
       },
       "bar":{
          "client":"127.0.0.1",
          "id":"23456",
          "start time":1654131900.997766
       }
    }
 }

I figured out how to loop through it like this:

for (var key in json) {
    if (json.hasOwnProperty(key)) {
        console.log(json[key])
    }
}

How can I loop through each sub element (foo and bar in this case) and then fetch a key, for example id?

client, id and start time are the only known key names

Expected output:

31971
23456

EDIT: The json comes from fetch:

setInterval(function () {
    fetch(<url>)
        .then(function (response) {
            return response.json();
        })
        .then(function (json) {
            for (var key in json) {
                if (json.hasOwnProperty(key)) {
                    console.log(json[key])
                }
            }
        })
}, 2000);

CodePudding user response:

Do another loop and grab the inner values by key name:

const json = {
    "dcf93893d83e4f28953f140b9cba1963":{
       "foo":{
          "client":"127.0.0.1",
          "id":"31971",
          "start time":1654131724.160335
       },
       "bar":{
          "client":"127.0.0.1",
          "id":"23456",
          "start time":1654131900.997766
       }
    }
 }
 
for (var key in json) {
    if (json.hasOwnProperty(key)) {
        //console.log(json[key])
        
        for(var key2 in json[key]) {
          console.log(json[key][key2]["id"])
        }
    }
}

CodePudding user response:

You have to loop in each loop. and save each id into an array.

var ids = []
for (var key in json) {
    if (json.hasOwnProperty(key)) {
        for(var obj in json[key]) {
           if (obj.id) ids.push(obj.id)
        }
    }
}

CodePudding user response:

Instead of iterating, you could just get the object's values with Object.values(), and map those accordingly using flatMap() and map():

const data = {
  "dcf93893d83e4f28953f140b9cba1963": {
    "foo": {
      "client": "127.0.0.1",
      "id": "31971",
      "start time": 1654131724.160335
    },
    "bar": {
      "client": "127.0.0.1",
      "id": "23456",
      "start time": 1654131900.997766
    }
  }
};

const result = Object.values(data)
                     .flatMap(v => Object.values(v)).map(({id}) => id);

console.log(result);

  • Related