Categories
JavaScript Answers

How to Find an Object Property by Key Deep in a Nested JavaScript Array?

Spread the love

To find an object property by key deep in a nested JavaScript array, we can traverse the deeply nested array with various loops and methods.

For instance, we can write:

const arr = [{
  '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': {
          //...
        }
      }]
    }]
  }]
}]

const customFilter = (object, key, value) => {
  if (Array.isArray(object)) {
    for (const obj of object) {
      const result = customFilter(obj, key, value);
      if (result) {
        return obj;
      }
    }
  } else {
    if (object.hasOwnProperty(key) && object[key] === value) {
      return object;
    }

    for (const k of Object.keys(object)) {
      if (typeof object[k] === "object") {
        const o = customFilter(object[k], key, value);
        if (o !== null && typeof o !== 'undefined')
          return o;
      }
    }

    return null;
  }
}

console.log(customFilter(arr, 'id', 1))

We have the deeply nested arr array that we want to check if an object with id property set to 1 exists.

To do that, we create the customFilter function that takes the object that we want to search, and the key and value that we want to look for in the object .

In the function, we check if object is an array with Array.isArray .

If it is, then we loop through the entries with the for-of loop and call customFilter with obj array entry, key and value .

Otherwise, if we found the key and value we’re looking for with:

object.hasOwnProperty(key) && object[key] === value

then we return the object.

Otherwise, we loop through the keys of the object with the for-of loop.

In the loop body, we check if the property value is an object with:

typeof object[k] === "object"

And if it is, we call customFilter on it with object[k] , key and value .

If the returned result of that isn’t null or undefined , we return the o object.

If we traverse the whole array and found no match, then we return null .

Therefore, the console log should log the entry found since it exists.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.