-4

I've got JSON like this:

{
  "245": {
    "data": {
      "userData": {
        "id": "61",
        "image": "http://example.com",
        "name": "John Smith",
        "friends": [
          {
            "invited": "67"
          },
          {
            "invited": "62"
          },
          {
            "invited": "65"
          },
          {
            "invited": "66"
          }
        ],
        "operator": true
      }
    }
  }
}

and I need to get "id" value from it. The first number ("245") is always different.

ancbrx
  • 11
  • 1
  • 2
    What have you tried so far to solve the problem? What was the problem with your attempt? – t.niese Sep 23 '18 at 12:05
  • If your problem is how to get the first number that will always change, then it is a duplicate to: [getting the first index of an object](https://stackoverflow.com/questions/909003/getting-the-first-index-of-an-object) – t.niese Sep 23 '18 at 12:10

3 Answers3

2

The JSON.parse reviver parameter can be used to check all properties :

var id, json = '{"245":{"data":{"userData":{"id":"61","image":"http://example.com","name":"John Smith","friends":[{"invited":"67"},{"invited":"62"},{"invited":"65"},{"invited":"66"}],"operator":true}}}}'

var obj = JSON.parse(json, (key, val) => key == 'id' ? id = val : val)

console.log( id )
Slai
  • 22,144
  • 5
  • 45
  • 53
1

If it has always this structure, you can get id by follow method:

var obj = {
  "245": {
    "data": {
      "userData": {
        "id": "61",
        "image": "http://example.com",
        "name": "John Smith",
        "friends": [
          {
            "invited": "67"
          },
          {
            "invited": "62"
          },
          {
            "invited": "65"
          },
          {
            "invited": "66"
          }
        ],
        "operator": true
      }
    }
  }
};
var result = Object.entries(obj);
console.log(result[0][1]["data"]["userData"]["id"])
protoproto
  • 2,081
  • 1
  • 13
  • 13
0

Unsure of what is the final output you are looking for. There are following approaches you can take. If you want all the key, id pairs try this where data is the your object.

const arr = [];
Object.keys(data).forEach((key, index) => {
  arr.push({ key, id: data[key].data.userData.id });
});
console.log(arr);

If you want just single value and you are sure that object structure would always have required keys use where key is "245".

const id = data[key].data.userData.id

If you want you can also take a look at lodash.get

const id = _.get(data[key], "data.userData.id", "NA");

https://lodash.com/docs/4.17.10#get

Shubham Gupta
  • 2,596
  • 1
  • 8
  • 19