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.
To use: let result = deepSearchByKey(arrayOrObject, 'key', 'value'); This will return the object containing the matching key and value.
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' }] };
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/
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With