[javascript] How can I access and process nested objects, arrays or JSON?

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?

This question is related to javascript arrays object nested data-manipulation

The answer is


Preliminaries

JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.

(Plain) Objects have the form

{key: value, key: value, ...}

Arrays have the form

[value, value, ...]

Both arrays and objects expose a key -> value structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".

Properties can be accessed either using dot notation

const value = obj.someProperty;

or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:

// the space is not a valid character in identifier names
const value = obj["some Property"];

// property name as variable
const name = "some Property";
const value = obj[name];

For that reason, array elements can only be accessed using bracket notation:

const value = arr[5]; // arr.5 would be a syntax error

// property name / index as variable
const x = 5;
const value = arr[x];

Wait... what about JSON?

JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .

Further reading material

How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections



Accessing nested data structures

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.

Here is an example:

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

Let's assume we want to access the name of the second item.

Here is how we can do it step-by-step:

As we can see data is an object, hence we can access its properties using dot notation. The items property is accessed as follows:

data.items

The value is an array, to access its second element, we have to use bracket notation:

data.items[1]

This value is an object and we use dot notation again to access the name property. So we eventually get:

const item_name = data.items[1].name;

Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:

const item_name = data['items'][1]['name'];

I'm trying to access a property but I get only undefined back?

Most of the time when you are getting undefined, the object/array simply doesn't have a property with that name.

const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined

Use console.log or console.dir and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.

console.log(foo.bar.baz); // 42

What if the property names are dynamic and I don't know them beforehand?

If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in [MDN] loop for objects and the for [MDN] loop for arrays to iterate over all properties / elements.

Objects

To iterate over all properties of data, we can iterate over the object like so:

for (const prop in data) {
    // `prop` contains the name of each property, i.e. `'code'` or `'items'`
    // consequently, `data[prop]` refers to the value of each property, i.e.
    // either `42` or the array
}

Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty [MDN].

As alternative to for...in with hasOwnProperty, you can use Object.keys [MDN] to get an array of property names:

Object.keys(data).forEach(function(prop) {
  // `prop` is the property name
  // `data[prop]` is the property value
});

Arrays

To iterate over all elements of the data.items array, we use a for loop:

for(let i = 0, l = data.items.length; i < l; i++) {
    // `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
    // we can access the next element in the array with `data.items[i]`, example:
    // 
    // var obj = data.items[i];
    // 
    // Since each element is an object (in our example),
    // we can now access the objects properties with `obj.id` and `obj.name`. 
    // We could also use `data.items[i].id`.
}

One could also use for...in to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.

With the increasing browser support of ECMAScript 5, the array method forEach [MDN] becomes an interesting alternative as well:

data.items.forEach(function(value, index, array) {
    // The callback is executed for each element in the array.
    // `value` is the element itself (equivalent to `array[index]`)
    // `index` will be the index of the element in the array
    // `array` is a reference to the array itself (i.e. `data.items` in this case)
}); 

In environments supporting ES2015 (ES6), you can also use the for...of [MDN] loop, which not only works for arrays, but for any iterable:

for (const item of data.items) {
   // `item` is the array element, **not** the index
}

In each iteration, for...of directly gives us the next element of the iterable, there is no "index" to access or use.


What if the "depth" of the data structure is unknown to me?

In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.

But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.

Here is an example to get the first leaf node of a binary tree:

function getLeaf(node) {
    if (node.leftChild) {
        return getLeaf(node.leftChild); // <- recursive call
    }
    else if (node.rightChild) {
        return getLeaf(node.rightChild); // <- recursive call
    }
    else { // node must be a leaf node
        return node;
    }
}

const first_leaf = getLeaf(root);

_x000D_
_x000D_
const root = {_x000D_
    leftChild: {_x000D_
        leftChild: {_x000D_
            leftChild: null,_x000D_
            rightChild: null,_x000D_
            data: 42_x000D_
        },_x000D_
        rightChild: {_x000D_
            leftChild: null,_x000D_
            rightChild: null,_x000D_
            data: 5_x000D_
        }_x000D_
    },_x000D_
    rightChild: {_x000D_
        leftChild: {_x000D_
            leftChild: null,_x000D_
            rightChild: null,_x000D_
            data: 6_x000D_
        },_x000D_
        rightChild: {_x000D_
            leftChild: null,_x000D_
            rightChild: null,_x000D_
            data: 7_x000D_
        }_x000D_
    }_x000D_
};_x000D_
function getLeaf(node) {_x000D_
    if (node.leftChild) {_x000D_
        return getLeaf(node.leftChild);_x000D_
    } else if (node.rightChild) {_x000D_
        return getLeaf(node.rightChild);_x000D_
    } else { // node must be a leaf node_x000D_
        return node;_x000D_
    }_x000D_
}_x000D_
_x000D_
console.log(getLeaf(root).data);
_x000D_
_x000D_
_x000D_

A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.

Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray again on that value (recursive call).

function toArray(obj) {
    const result = [];
    for (const prop in obj) {
        const value = obj[prop];
        if (typeof value === 'object') {
            result.push(toArray(value)); // <- recursive call
        }
        else {
            result.push(value);
        }
    }
    return result;
}

_x000D_
_x000D_
const data = {_x000D_
  code: 42,_x000D_
  items: [{_x000D_
    id: 1,_x000D_
    name: 'foo'_x000D_
  }, {_x000D_
    id: 2,_x000D_
    name: 'bar'_x000D_
  }]_x000D_
};_x000D_
_x000D_
_x000D_
function toArray(obj) {_x000D_
  const result = [];_x000D_
  for (const prop in obj) {_x000D_
    const value = obj[prop];_x000D_
    if (typeof value === 'object') {_x000D_
      result.push(toArray(value));_x000D_
    } else {_x000D_
      result.push(value);_x000D_
    }_x000D_
  }_x000D_
  return result;_x000D_
}_x000D_
_x000D_
console.log(toArray(data));
_x000D_
_x000D_
_x000D_



Helpers

Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log [MDN] and console.dir [MDN] help us doing this. For example (output of the Chrome console):

> console.log(data.items)
 [ Object, Object ]

Here we see that that data.items is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.

> console.log(data.items[1])
  Object
     id: 2
     name: "bar"
     __proto__: Object

This tells us that data.items[1] is an object, and after expanding it we see that it has three properties, id, name and __proto__. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.


It's simple explanation:

_x000D_
_x000D_
var data = {_x000D_
    code: 42,_x000D_
    items: [{_x000D_
        id: 1,_x000D_
        name: 'foo'_x000D_
    }, {_x000D_
        id: 2,_x000D_
        name: 'bar'_x000D_
    }]_x000D_
};_x000D_
_x000D_
/*_x000D_
1. `data` is object contain `item` object*/_x000D_
console.log(data);_x000D_
_x000D_
/*_x000D_
2. `item` object contain array of two objects as elements*/_x000D_
console.log(data.items);_x000D_
_x000D_
/*_x000D_
3. you need 2nd element of array - the `1` from `[0, 1]`*/_x000D_
console.log(data.items[1]);_x000D_
_x000D_
/*_x000D_
4. and you need value of `name` property of 2nd object-element of array)*/_x000D_
console.log(data.items[1].name);
_x000D_
_x000D_
_x000D_


At times, accessing a nested object using a string can be desirable. The simple approach is the first level, for example

var obj = { hello: "world" };
var key = "hello";
alert(obj[key]);//world

But this is often not the case with complex json. As json becomes more complex, the approaches for finding values inside of the json also become complex. A recursive approach for navigating the json is best, and how that recursion is leveraged will depend on the type of data being searched for. If there are conditional statements involved, a json search can be a good tool to use.

If the property being accessed is already known, but the path is complex, for example in this object

var obj = {
 arr: [
    { id: 1, name: "larry" },    
    { id: 2, name: "curly" },
    { id: 3, name: "moe" }
 ]
};

And you know you want to get the first result of the array in the object, perhaps you would like to use

var moe = obj["arr[0].name"];

However, that will cause an exception as there is no property of object with that name. The solution to be able to use this would be to flatten the tree aspect of the object. This can be done recursively.

function flatten(obj){
 var root = {};
 (function tree(obj, index){
   var suffix = toString.call(obj) == "[object Array]" ? "]" : "";
   for(var key in obj){
    if(!obj.hasOwnProperty(key))continue;
    root[index+key+suffix] = obj[key];
    if( toString.call(obj[key]) == "[object Array]" )tree(obj[key],index+key+suffix+"[");
    if( toString.call(obj[key]) == "[object Object]" )tree(obj[key],index+key+suffix+".");   
   }
 })(obj,"");
 return root;
}

Now, the complex object can be flattened

var obj = previous definition;
var flat = flatten(obj);
var moe = flat["arr[0].name"];//moe

Here is a jsFiddle Demo of this approach being used.


A pythonic, recursive and functional approach to unravel arbitrary JSON trees:

handlers = {
    list:  iterate,
    dict:  delve,
    str:   emit_li,
    float: emit_li,
}

def emit_li(stuff, strong=False):
    emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
    print(emission % stuff)

def iterate(a_list):
    print('<ul>')
    map(unravel, a_list)
    print('</ul>')

def delve(a_dict):
    print('<ul>')
    for key, value in a_dict.items():
        emit_li(key, strong=True)
        unravel(value)
    print('</ul>')

def unravel(structure):
    h = handlers[type(structure)]
    return h(structure)

unravel(data)

where data is a python list (parsed from a JSON text string):

data = [
    {'data': {'customKey1': 'customValue1',
           'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
  'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
               'viewport': {'northeast': {'lat': 37.4508789,
                                          'lng': -122.0446721},
                            'southwest': {'lat': 37.3567599,
                                          'lng': -122.1178619}}},
  'name': 'Mountain View',
  'scope': 'GOOGLE',
  'types': ['locality', 'political']}
]

You could use lodash _get function:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// => 3

You can use the syntax jsonObject.key to access the the value. And if you want access a value from an array, then you can use the syntax jsonObjectArray[index].key.

Here are the code examples to access various values to give you the idea.

_x000D_
_x000D_
        var data = {_x000D_
            code: 42,_x000D_
            items: [{_x000D_
                id: 1,_x000D_
                name: 'foo'_x000D_
            }, {_x000D_
                id: 2,_x000D_
                name: 'bar'_x000D_
            }]_x000D_
        };_x000D_
_x000D_
        // if you want 'bar'_x000D_
        console.log(data.items[1].name);_x000D_
_x000D_
        // if you want array of item names_x000D_
        console.log(data.items.map(x => x.name));_x000D_
_x000D_
        // get the id of the item where name = 'bar'_x000D_
        console.log(data.items.filter(x => (x.name == "bar") ? x.id : null)[0].id);
_x000D_
_x000D_
_x000D_


Here are 4 different methods mentioned to get the object property:

_x000D_
_x000D_
var data = {
  code: 42,
  items: [{
    id: 1,
    name: 'foo'
  }, {
    id: 2,
    name: 'bar'
  }]
};
// Method 1
let method1 = data.items[1].name;
console.log(method1);

// Method 2
let method2 = data.items[1]["name"];
console.log(method2);

// Method 3
let method3 = data["items"][1]["name"];
console.log(method3);

// Method 4  Destructuring
let { items: [, { name: second_name }] } = data;
console.log(second_name);
_x000D_
_x000D_
_x000D_


Objects and arrays has a lot of built-in methods that can help you with processing data.

Note: in many of the examples I'm using arrow functions. They are similar to function expressions, but they bind the this value lexically.

Object.keys(), Object.values() (ES 2017) and Object.entries() (ES 2017)

Object.keys() returns an array of object's keys, Object.values() returns an array of object's values, and Object.entries() returns an array of object's keys and corresponding values in a format [key, value].

_x000D_
_x000D_
const obj = {_x000D_
  a: 1_x000D_
 ,b: 2_x000D_
 ,c: 3_x000D_
}_x000D_
_x000D_
console.log(Object.keys(obj)) // ['a', 'b', 'c']_x000D_
console.log(Object.values(obj)) // [1, 2, 3]_x000D_
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
_x000D_
_x000D_
_x000D_

Object.entries() with a for-of loop and destructuring assignment

_x000D_
_x000D_
const obj = {_x000D_
  a: 1_x000D_
 ,b: 2_x000D_
 ,c: 3_x000D_
}_x000D_
_x000D_
for (const [key, value] of Object.entries(obj)) {_x000D_
  console.log(`key: ${key}, value: ${value}`)_x000D_
}
_x000D_
_x000D_
_x000D_

It's very convenient to iterate the result of Object.entries() with a for-of loop and destructuring assignment.

For-of loop lets you iterate array elements. The syntax is for (const element of array) (we can replace const with var or let, but it's better to use const if we don't intend to modify element).

Destructuring assignment lets you extract values from an array or an object and assign them to variables. In this case const [key, value] means that instead of assigning the [key, value] array to element, we assign the first element of that array to key and the second element to value. It is equivalent to this:

for (const element of Object.entries(obj)) {
  const key = element[0]
       ,value = element[1]
}

As you can see, destructuring makes this a lot simpler.

Array.prototype.every() and Array.prototype.some()

The every() method returns true if the specified callback function returns true for every element of the array. The some() method returns true if the specified callback function returns true for some (at least one) element.

_x000D_
_x000D_
const arr = [1, 2, 3]_x000D_
_x000D_
// true, because every element is greater than 0_x000D_
console.log(arr.every(x => x > 0))_x000D_
// false, because 3^2 is greater than 5_x000D_
console.log(arr.every(x => Math.pow(x, 2) < 5))_x000D_
// true, because 2 is even (the remainder from dividing by 2 is 0)_x000D_
console.log(arr.some(x => x % 2 === 0))_x000D_
// false, because none of the elements is equal to 5_x000D_
console.log(arr.some(x => x === 5))
_x000D_
_x000D_
_x000D_

Array.prototype.find() and Array.prototype.filter()

The find() methods returns the first element which satisfies the provided callback function. The filter() method returns an array of all elements which satisfies the provided callback function.

_x000D_
_x000D_
const arr = [1, 2, 3]_x000D_
_x000D_
// 2, because 2^2 !== 2_x000D_
console.log(arr.find(x => x !== Math.pow(x, 2)))_x000D_
// 1, because it's the first element_x000D_
console.log(arr.find(x => true))_x000D_
// undefined, because none of the elements equals 7_x000D_
console.log(arr.find(x => x === 7))_x000D_
_x000D_
// [2, 3], because these elements are greater than 1_x000D_
console.log(arr.filter(x => x > 1))_x000D_
// [1, 2, 3], because the function returns true for all elements_x000D_
console.log(arr.filter(x => true))_x000D_
// [], because none of the elements equals neither 6 nor 7_x000D_
console.log(arr.filter(x => x === 6 || x === 7))
_x000D_
_x000D_
_x000D_

Array.prototype.map()

The map() method returns an array with the results of calling a provided callback function on the array elements.

_x000D_
_x000D_
const arr = [1, 2, 3]_x000D_
_x000D_
console.log(arr.map(x => x + 1)) // [2, 3, 4]_x000D_
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']_x000D_
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)_x000D_
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]_x000D_
console.log(arr.map(String)) // ['1', '2', '3']
_x000D_
_x000D_
_x000D_

Array.prototype.reduce()

The reduce() method reduces an array to a single value by calling the provided callback function with two elements.

_x000D_
_x000D_
const arr = [1, 2, 3]_x000D_
_x000D_
// Sum of array elements._x000D_
console.log(arr.reduce((a, b) => a + b)) // 6_x000D_
// The largest number in the array._x000D_
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
_x000D_
_x000D_
_x000D_

The reduce() method takes an optional second parameter, which is the initial value. This is useful when the array on which you call reduce() can has zero or one elements. For example, if we wanted to create a function sum() which takes an array as an argument and returns the sum of all elements, we could write it like that:

_x000D_
_x000D_
const sum = arr => arr.reduce((a, b) => a + b, 0)_x000D_
_x000D_
console.log(sum([]))     // 0_x000D_
console.log(sum([4]))    // 4_x000D_
console.log(sum([2, 5])) // 7
_x000D_
_x000D_
_x000D_


// const path = 'info.value[0].item'
// const obj = { info: { value: [ { item: 'it works!' } ], randominfo: 3 }  }
// getValue(path, obj)

export const getValue = ( path , obj) => {
  const newPath = path.replace(/\]/g, "")
  const arrayPath = newPath.split(/[\[\.]+/) || newPath;

  const final = arrayPath.reduce( (obj, k) => obj ?  obj[k] : obj, obj)
  return final;
}

I prefer JQuery. It's cleaner and easy to read.

$.each($.parseJSON(data), function (key, value) {
  alert(value.<propertyname>);
});

Using lodash would be good solution

Ex:

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

This question is quite old, so as a contemporary update. With the onset of ES2015 there are alternatives to get a hold of the data you require. There is now a feature called object destructuring for accessing nested objects.

_x000D_
_x000D_
const data = {_x000D_
  code: 42,_x000D_
  items: [{_x000D_
    id: 1,_x000D_
    name: 'foo'_x000D_
  }, {_x000D_
    id: 2,_x000D_
    name: 'bar'_x000D_
  }]_x000D_
};_x000D_
_x000D_
const {_x000D_
  items: [, {_x000D_
    name: secondName_x000D_
  }]_x000D_
} = data;_x000D_
_x000D_
console.log(secondName);
_x000D_
_x000D_
_x000D_

The above example creates a variable called secondName from the name key from an array called items, the lonely , says skip the first object in the array.

Notably it's probably overkill for this example, as simple array acccess is easier to read, but it comes in useful when breaking apart objects in general.

This is very brief intro to your specific use case, destructuring can be an unusual syntax to get used to at first. I'd recommend reading Mozilla's Destructuring Assignment documentation to learn more.


In case you're trying to access an item from the example structure by id or name, without knowing it's position in the array, the easiest way to do it would be to use underscore.js library:

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

_.find(data.items, function(item) {
  return item.id === 2;
});
// Object {id: 2, name: "bar"}

From my experience, using higher order functions instead of for or for..in loops results in code that is easier to reason about, and hence more maintainable.

Just my 2 cents.


Here is an answer using object-scan.

When accessing a single entry, this answer doesn't really provide much benefit over vanilla javascript. However interacting with multiple fields at the same time this answer can be more performant.

Here is how you could interact with a single field

_x000D_
_x000D_
// const objectScan = require('object-scan');

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

const get = (haystack, needle) => objectScan([needle], {
  abort: true,
  rtn: 'value'
})(haystack);

const set = (haystack, needle, value) => objectScan([needle], {
  abort: true,
  rtn: 'bool',
  filterFn: ({ parent, property }) => {
    parent[property] = value;
    return true;
  }
})(haystack);

console.log(get(data, 'items[1].name'));
// => bar

console.log(set(data, 'items[1].name', 'foo2'));
// => true
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo' }, { id: 2, name: 'foo2' } ] }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_

Disclaimer: I'm the author of object-scan

and here is how you could interact with multiple fields at the same time

_x000D_
_x000D_
// const objectScan = require('object-scan');

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

const get = (haystack, ...needles) => objectScan(needles, {
  joined: true,
  rtn: 'entry'
})(haystack);

const set = (haystack, actions) => objectScan(Object.keys(actions), {
  rtn: 'count',
  filterFn: ({ matchedBy, parent, property }) => {
    matchedBy.forEach((m) => {
      parent[property] = actions[m];
    })
    return true;
  }
})(haystack);

console.log(get(data, 'items[0].name', 'items[1].name'));
// => [ [ 'items[1].name', 'bar' ], [ 'items[0].name', 'foo' ] ]

console.log(set(data, {
  'items[0].name': 'foo1',
  'items[1].name': 'foo2'
}));
// => 2
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo1' }, { id: 2, name: 'foo2' } ] }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_

Disclaimer: I'm the author of object-scan


And here is how one could find an entity in a deeply nested object searching by id (as asked in comment)

_x000D_
_x000D_
// const objectScan = require('object-scan');

const myData = { code: 42, items: [{ id: 1, name: 'aaa', items: [{ id: 3, name: 'ccc' }, { id: 4, name: 'ddd' }] }, { id: 2, name: 'bbb', items: [{ id: 5, name: 'eee' }, { id: 6, name: 'fff' }] }] };

const findItemById = (haystack, id) => objectScan(['**(^items$).id'], {
  abort: true,
  useArraySelector: false,
  rtn: 'parent',
  filterFn: ({ value }) => value === id
})(haystack);

console.log(findItemById(myData, 5));
// => { id: 5, name: 'eee' }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_

Disclaimer: I'm the author of object-scan


If you are looking for one or more objects that meets certain criteria you have a few options using query-js

//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1 
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});

There's also a single and a singleOrDefault they work much like firstand firstOrDefaultrespectively. The only difference is that they will throw if more than one match is found.

for further explanation of query-js you can start with this post


To access a nested attribute, you need to specify its name and then search through the object.

If you already know the exact path, then you can hardcode it in your script like so:

data['items'][1]['name']

these also work -

data.items[1].name
data['items'][1].name
data.items[1]['name']

When you don't know the exact name before hand, or a user is the one who provides the name for you. Then dynamically searching through the data structure is required. Some suggested here that the search can be done using a for loop, but there is a very simple way to traverse a path using Array.reduce.

const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }
const path = [ 'items', '1', 'name']
let result = path.reduce((a,v) => a[v], data)

The path is a way to say: First take the object with key items, which happens to be an array. Then take the 1-st element (0 index arrays). Last take the object with key name in that array element, which happens to be the string bar.

If you have a very long path, you might even use String.split to make all of this easier -

'items.1.name'.split('.').reduce((a,v) => a[v], data)

This is just plain JavaScript, without using any third party libraries like jQuery or lodash.


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);

Accessing dynamically multi levels object.

var obj = {
  name: "john doe",
  subobj: {
    subsubobj: {
      names: "I am sub sub obj"
    }
  }
};

var level = "subobj.subsubobj.names";
level = level.split(".");

var currentObjState = obj;

for (var i = 0; i < level.length; i++) {
  currentObjState = currentObjState[level[i]];
}

console.log(currentObjState);

Working fiddle: https://jsfiddle.net/andreitodorut/3mws3kjL/


jQuery's grep function lets you filter through an array:

_x000D_
_x000D_
var data = {_x000D_
    code: 42,_x000D_
    items: [{_x000D_
        id: 1,_x000D_
        name: 'foo'_x000D_
    }, {_x000D_
        id: 2,_x000D_
        name: 'bar'_x000D_
    }]_x000D_
};_x000D_
_x000D_
$.grep(data.items, function(item) {_x000D_
    if (item.id === 2) {_x000D_
        console.log(item.id); //console id of item_x000D_
        console.log(item.name); //console name of item_x000D_
        console.log(item); //console item object_x000D_
        return item; //returns item object_x000D_
    }_x000D_
_x000D_
});_x000D_
// Object {id: 2, name: "bar"}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


Using JSONPath would be one of the most flexible solutions if you are willing to include a library: https://github.com/s3u/JSONPath (node and browser)

For your use case the json path would be:

$..items[1].name

so:

var secondName = jsonPath.eval(data, "$..items[1].name");

Dynamic approach

In below deep(data,key) function, you can use arbitrary key string - in your case items[1].name (you can use array notation [i] at any level) - if key is invalid then undefined is return.

_x000D_
_x000D_
let deep = (o,k) => k.split('.').reduce((a,c,i) => {_x000D_
    let m=c.match(/(.*?)\[(\d*)\]/);_x000D_
    if(m && a!=null && a[m[1]]!=null) return a[m[1]][+m[2]];_x000D_
    return a==null ? a: a[c];_x000D_
},o);_x000D_
_x000D_
// TEST_x000D_
_x000D_
let key = 'items[1].name' // arbitrary deep-key_x000D_
_x000D_
let data = {_x000D_
    code: 42,_x000D_
    items: [{ id: 11, name: 'foo'}, { id: 22, name: 'bar'},]_x000D_
};_x000D_
_x000D_
console.log( key,'=', deep(data,key) );
_x000D_
_x000D_
_x000D_


Just in case, anyone's visiting this question in 2017 or later and looking for an easy-to-remember way, here's an elaborate blog post on Accessing Nested Objects in JavaScript without being bamboozled by

Cannot read property 'foo' of undefined error

1. Oliver Steele's nested object access pattern

The easiest and the cleanest way is to use Oliver Steele's nested object access pattern

const name = ((user || {}).personalInfo || {}).name;

With this notation, you'll never run into

Cannot read property 'name' of undefined.

You basically check if user exists, if not, you create an empty object on the fly. This way, the next level key will always be accessed from an object that exists or an empty object, but never from undefined.

2. Access Nested Objects Using Array Reduce

To be able to access nested arrays, you can write your own array reduce util.

const getNestedObject = (nestedObj, pathArr) => {
    return pathArr.reduce((obj, key) =>
        (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}

// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);

// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'addresses', 0, 'city']);
// this will return the city from the first address item.

There is also an excellent type handling minimal library typy that does all this for you.


You can access it this way

data.items[1].name

or

data["items"][1]["name"]

Both ways are equal.


In 2020, you can use @babel/plugin-proposal-optional-chaining it is very easy to access nested values in an object.

 const obj = {
 foo: {
   bar: {
     baz: class {
   },
  },
 },
};

const baz = new obj?.foo?.bar?.baz(); // baz instance

const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined

https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining

https://github.com/tc39/proposal-optional-chaining


I don't think questioner just only concern one level nested object, so I present the following demo to demonstrate how to access the node of deeply nested json object. All right, let's find the node with id '5'.

_x000D_
_x000D_
var data = {_x000D_
  code: 42,_x000D_
  items: [{_x000D_
    id: 1,_x000D_
    name: 'aaa',_x000D_
    items: [{_x000D_
        id: 3,_x000D_
        name: 'ccc'_x000D_
      }, {_x000D_
        id: 4,_x000D_
        name: 'ddd'_x000D_
      }]_x000D_
    }, {_x000D_
    id: 2,_x000D_
    name: 'bbb',_x000D_
    items: [{_x000D_
        id: 5,_x000D_
        name: 'eee'_x000D_
      }, {_x000D_
        id: 6,_x000D_
        name: 'fff'_x000D_
      }]_x000D_
    }]_x000D_
};_x000D_
_x000D_
var jsonloop = new JSONLoop(data, 'id', 'items');_x000D_
_x000D_
jsonloop.findNodeById(data, 5, function(err, node) {_x000D_
  if (err) {_x000D_
    document.write(err);_x000D_
  } else {_x000D_
    document.write(JSON.stringify(node, null, 2));_x000D_
  }_x000D_
});
_x000D_
<script src="https://rawgit.com/dabeng/JSON-Loop/master/JSONLoop.js"></script>
_x000D_
_x000D_
_x000D_


The Underscore js Way

Which is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.

Solution:

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

var item = _.findWhere(data.items, {
  id: 2
});
if (!_.isUndefined(item)) {
  console.log('NAME =>', item.name);
}

//using find - 

var item = _.find(data.items, function(item) {
  return item.id === 2;
});

if (!_.isUndefined(item)) {
  console.log('NAME =>', item.name);
}

var ourStorage = {


"desk":    {
    "drawer": "stapler"
  },
"cabinet": {
    "top drawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  }
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"

or

//parent.subParent.subsubParent["almost there"]["final property"]

Basically, use a dot between each descendant that unfolds underneath it and when you have object names made out of two strings, you must use the ["obj Name"] notation. Otherwise, just a dot would suffice;

Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects

to add to this, accessing nested Arrays would happen like so:

var ourPets = [
  {
    animalType: "cat",
    names: [
      "Meowzer",
      "Fluffy",
      "Kit-Cat"
    ]
  },
  {
    animalType: "dog",
    names: [
      "Spot",
      "Bowser",
      "Frankie"
    ]
  }
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"

Source: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/

Another more useful document depicting the situation above: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation

Property access via dot walking: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation


Old question but as nobody mentioned lodash (just underscore).

In case you are already using lodash in your project, I think an elegant way to do this in a complex example:

Opt 1

_.get(response, ['output', 'fund', 'data', '0', 'children', '0', 'group', 'myValue'], '')

same as:

Opt 2

response.output.fund.data[0].children[0].group.myValue

The difference between the first and second option is that in the Opt 1 if you have one of the properties missing (undefined) in the path you don't get an error, it returns you the third parameter.

For array filter lodash has _.find() but I'd rather use the regular filter(). But I still think the above method _.get() is super useful when working with really complex data. I faced in the past really complex APIs and it was handy!

I hope it can be useful for who's looking for options to manipulate really complex data which the title implies.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to nested

Nested routes with react router v4 / v5 Extract first item of each sublist python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" How can I combine multiple nested Substitute functions in Excel? Retrieving values from nested JSON Object MySQL Nested Select Query? List comprehension on a nested list? Nested ifelse statement Single Line Nested For Loops Nested or Inner Class in PHP

Examples related to data-manipulation

Converting String Array to an Integer Array How can I access and process nested objects, arrays or JSON? How do I remove objects from an array in Java? Removing elements with Array.map in JavaScript