Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find by key deep in a nested array

Let's say I have an object:

[     {         'title': "some title"         'channel_id':'123we'         'options': [                     {                 'channel_id':'abc'                 'image':'http://asdasd.com/all-inclusive-block-img.jpg'                 'title':'All-Inclusive'                 'options':[                     {                         'channel_id':'dsa2'                         'title':'Some Recommends'                         'options':[                             {                                 'image':'http://www.asdasd.com'                                 'title':'Sandals'                                 'id':'1'                                 'content':{                                      ... 

I want to find the one object where the id is 1. Is there a function for something like this? I could use Underscore's _.filter method, but I would have to start at the top and filter down.

like image 356
Harry Avatar asked Mar 20 '13 12:03

Harry


People also ask

How do you find the object property by key deep in a nested JavaScript array?

To use: let result = deepSearchByKey(arrayOrObject, 'key', 'value'); This will return the object containing the matching key and value.

How do I find the value of a nested object?

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


2 Answers

Recursion is your friend. I updated the function to account for property arrays:

function getObject(theObject) {     var result = null;     if(theObject instanceof Array) {         for(var i = 0; i < theObject.length; i++) {             result = getObject(theObject[i]);             if (result) {                 break;             }            }     }     else     {         for(var prop in theObject) {             console.log(prop + ': ' + theObject[prop]);             if(prop == 'id') {                 if(theObject[prop] == 1) {                     return theObject;                 }             }             if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {                 result = getObject(theObject[prop]);                 if (result) {                     break;                 }             }          }     }     return result; } 

updated jsFiddle: http://jsfiddle.net/FM3qu/7/

like image 55
Zach Avatar answered Oct 12 '22 14:10

Zach


What worked for me was this lazy approach, not algorithmically lazy ;)

if( JSON.stringify(object_name).indexOf("key_name") > -1 ) {     console.log("Key Found"); } else{     console.log("Key not Found"); } 
like image 42
abhinav1602 Avatar answered Oct 12 '22 14:10

abhinav1602