Find by key deep in a nested array

后端 未结 17 1331
礼貌的吻别
礼貌的吻别 2020-11-22 15:41

Let\'s say I have an object:

[
    {
        \'title\': \"some title\"
        \'channel_id\':\'123we\'
        \'options\': [
                    {
                 


        
17条回答
  •  抹茶落季
    2020-11-22 15:45

    Improved @haitaka answer, using the key and predicate

    function  deepSearch (object, key, predicate) {
        if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) return object
    
        for (let i = 0; i < Object.keys(object).length; i++) {
          let value = object[Object.keys(object)[i]];
          if (typeof value === "object" && value != null) {
            let o = deepSearch(object[Object.keys(object)[i]], key, predicate)
            if (o != null) return o
          }
        }
        return null
    }
    

    So this can be invoked as:

    var result = deepSearch(myObject, 'id', (k, v) => v === 1);
    

    or

    var result = deepSearch(myObject, 'title', (k, v) => v === 'Some Recommends');
    

    Here is the demo: http://jsfiddle.net/a21dx6c0/

    EDITED

    In the same way you can find more than one object

    function deepSearchItems(object, key, predicate) {
            let ret = [];
            if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) {
                ret = [...ret, object];
            }
            if (Object.keys(object).length) {
                for (let i = 0; i < Object.keys(object).length; i++) {
                    let value = object[Object.keys(object)[i]];
                    if (typeof value === "object" && value != null) {
                        let o = this.deepSearchItems(object[Object.keys(object)[i]], key, predicate);
                        if (o != null && o instanceof Array) {
                            ret = [...ret, ...o];
                        }
                    }
                }
            }
            return ret;
        }
    

提交回复
热议问题