1135

I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?

For example:

var data = {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
};

How could I access the name of the second item in items?

3
  • 32
    @Marcel: It has to be read as "I have a data nested data structure or JSON, how can I access a specific value?". I know the difference, but many people don't and might be searching for "JSON" rather than "object". Many questions actually are of the form "how can I access X in this JSON". The only place where I mention JSON in my answer is where I explain what it is. If you have a suggestion how to communicate this in a better way, I'm all ears. Commented Mar 2, 2013 at 0:46
  • 1
    There are so many way to access specific name in array of objects in object. for this scenario you can access it using "data.items[1].name" and for any custom name and other item you can use it this way "data.items[i][nameofvariable] . here i is position in array and nameofvariable is key which you want to access. for more detail about accessing you can check this link thecodingcloud.com/…
    – ammy
    Commented Feb 21, 2023 at 5:29
  • Another handy and tiny library, SelectQL.js is inspired by Structured Query Language (SQL) for accessing and manipulating Objects in an easy and familiar way. It supports complex Objects and Arrays using Builder Design Pattern. npmjs.com/package/selectql.js
    – Nadeem
    Commented Feb 25, 2023 at 18:26

32 Answers 32

1
2
-4

My stringdata is coming from PHP file but still, I indicate here in var. When i directly take my json into obj it will nothing show thats why i put my json file as

var obj=JSON.parse(stringdata); so after that i get message obj and show in alert box then I get data which is json array and store in one varible ArrObj then i read first object of that array with key value like this ArrObj[0].id

     var stringdata={
        "success": true,
        "message": "working",
        "data": [{
                  "id": 1,
                  "name": "foo"
         }]
      };

                var obj=JSON.parse(stringdata);
                var key = "message";
                alert(obj[key]);
                var keyobj = "data";
                var ArrObj =obj[keyobj];

                alert(ArrObj[0].id);
1
  • 4
    The example is confusing because stringjson is not a string. Commented Apr 4, 2019 at 15:56
-5

Using lodash would be good solution

Ex:

var object = { 'a': { 'b': { 'c': 3 } } };                                                                                               
_.get(object, 'a.b.c');                                                                                             
// => 3  
2
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.