Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing nested JavaScript objects and arrays by string path

I have a data structure like this :

var someObject = {     'part1' : {         'name': 'Part 1',         'size': '20',         'qty' : '50'     },     'part2' : {         'name': 'Part 2',         'size': '15',         'qty' : '60'     },     'part3' : [         {             'name': 'Part 3A',             'size': '10',             'qty' : '20'         }, {             'name': 'Part 3B',             'size': '5',             'qty' : '20'         }, {             'name': 'Part 3C',             'size': '7.5',             'qty' : '20'         }     ] }; 

And I would like to access the data using these variable :

var part1name = "part1.name"; var part2quantity = "part2.qty"; var part3name1 = "part3[0].name"; 

part1name should be filled with someObject.part1.name 's value, which is "Part 1". Same thing with part2quantity which filled with 60.

Is there anyway to achieve this with either pure javascript or JQuery?

like image 280
Komaruloh Avatar asked Jun 27 '11 10:06

Komaruloh


People also ask

How do you access nested array of objects?

You can access a nested array of objects either using dot notation or bracket notation. JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of an object. Both arrays and objects expose a key -> value structure.

How do you access data from nested objects?

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' }] };

Can you nest objects in JavaScript?

You can create nested objects within a nested object. In the following example, Salary is an object that resides inside the main object named Employee . The dot notation can access the property of nested objects.


2 Answers

I just made this based on some similar code I already had, it appears to work:

Object.byString = function(o, s) {     s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties     s = s.replace(/^\./, '');           // strip a leading dot     var a = s.split('.');     for (var i = 0, n = a.length; i < n; ++i) {         var k = a[i];         if (k in o) {             o = o[k];         } else {             return;         }     }     return o; } 

Usage::

Object.byString(someObj, 'part3[0].name'); 

See a working demo at http://jsfiddle.net/alnitak/hEsys/

EDIT some have noticed that this code will throw an error if passed a string where the left-most indexes don't correspond to a correctly nested entry within the object. This is a valid concern, but IMHO best addressed with a try / catch block when calling, rather than having this function silently return undefined for an invalid index.

like image 183
Alnitak Avatar answered Sep 19 '22 03:09

Alnitak


This is now supported by lodash using _.get(obj, property). See https://lodash.com/docs#get

Example from the docs:

var object = { 'a': [{ 'b': { 'c': 3 } }] };  _.get(object, 'a[0].b.c'); // → 3  _.get(object, ['a', '0', 'b', 'c']); // → 3  _.get(object, 'a.b.c', 'default'); // → 'default' 
like image 27
Ian Walker-Sperber Avatar answered Sep 22 '22 03:09

Ian Walker-Sperber