B
B
BonBon Slick2020-02-12 19:07:48
JavaScript
BonBon Slick, 2020-02-12 19:07:48

How to find recursively an object or array by key and value?

/**
 * @param {array|Object}searchInArray
 * @param {string|int} searchKey
 * @param {string|int} searchValue
 *
 *  @todo - use lodash?
 *
 * @return {Object}
 */
function walkRecursive ({searchInArray, searchKey, searchValue}) {
    let returnValue = {};
    if (false === Array.isArray(searchInArray)) {
        searchInArray = Object.keys(searchInArray).map(function (key) {
            let keyValArr = [];
            return keyValArr[key] = searchInArray[key];
        });
    }
    searchInArray.some(function checkArray (arrayItem) {
        if (searchValue === arrayItem[searchKey]) {
            returnValue = arrayItem;

            return true;
        }

        return Array.isArray(arrayItem.children) && arrayItem.children.some(checkArray);
    });

    return returnValue;
}


My current example works with simple arrays, I'm trying to refine it for objects and I'm already a bit tired.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-02-12
@BonBonSlick

const find = (obj, key, val) =>
  obj instanceof Object
    ? obj.hasOwnProperty(key) && Object.is(obj[key], val)
      ? obj
      : Object.values(obj).reduce((found, n) => found || find(n, key, val), null)
    : null;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question