在嵌套数组中的深层按键查找

vxbzzdmp  于 2022-09-21  发布在  Node.js
关注(0)|答案(22)|浏览(245)

假设我有一个物体:

[
    {
        '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':{
                                     ...

我想找一个id为1的对象。有这样的函数吗?我可以使用下划线的_.filter方法,但我必须从顶部开始并向下过滤。

eeq64g8w

eeq64g8w1#

递归是你的朋友。我更新了该函数以说明属性数组:

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

已更新jsFdle:http://jsfiddle.net/FM3qu/7/

7d7tgy0s

7d7tgy0s2#

对我来说起作用的是这种懒惰的方法,而不是算法上的懒惰;)

if( JSON.stringify(object_name).indexOf("key_name") > -1 ) {
    console.log("Key Found");
}
else{
    console.log("Key not Found");
}
piztneat

piztneat3#

另一个(有些愚蠢的)选择是利用JSON.stringify的自然递归特性,并向其传递一个替换函数,该函数在字符串化过程中在每个嵌套对象上运行:

const input = [{
  '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': {}
      }]
    }]
  }]
}];

console.log(findNestedObj(input, 'id', '1'));

function findNestedObj(entireObj, keyToFind, valToFind) {
  let foundObj;
  JSON.stringify(entireObj, (_, nestedValue) => {
    if (nestedValue && nestedValue[keyToFind] === valToFind) {
      foundObj = nestedValue;
    }
    return nestedValue;
  });
  return foundObj;
};
qc6wkl3g

qc6wkl3g4#

如果您想在搜索Object时获取id为1的第一个元素,可以使用以下函数:

function customFilter(object){
    if(object.hasOwnProperty('id') && object["id"] == 1)
        return object;

    for(var i=0; i<Object.keys(object).length; i++){
        if(typeof object[Object.keys(object)[i]] == "object"){
            var o = customFilter(object[Object.keys(object)[i]]);
            if(o != null)
                return o;
        }
    }

    return null;
}

如果要获取id为1的所有元素,则(id为1的所有元素都存储在Result中,如您所见):

function customFilter(object, result){
    if(object.hasOwnProperty('id') && object.id == 1)
        result.push(object);

    for(var i=0; i<Object.keys(object).length; i++){
        if(typeof object[Object.keys(object)[i]] == "object"){
            customFilter(object[Object.keys(object)[i]], result);
        }
    }
}
f2uvfpb9

f2uvfpb95#

改进了@haitaka答案,使用了键和 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
}

因此,可以按如下方式调用:

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

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

以下是演示:http://jsfiddle.net/a21dx6c0/

已编辑

同样,您可以找到不止一个对象

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;
    }
px9o7tmv

px9o7tmv6#

我通过谷歌搜索找到了这个页面,寻找类似的功能。基于Zach和Regarmike提供的工作,我创建了另一个适合我需求的版本。
顺便说一句,交通工作和规则!我将在此处发布代码:

function findObjects(obj, targetProp, targetValue, finalResults) {

  function getObject(theObject) {
    let result = null;
    if (theObject instanceof Array) {
      for (let i = 0; i < theObject.length; i++) {
        getObject(theObject[i]);
      }
    }
    else {
      for (let prop in theObject) {
        if(theObject.hasOwnProperty(prop)){
          console.log(prop + ': ' + theObject[prop]);
          if (prop === targetProp) {
            console.log('--found id');
            if (theObject[prop] === targetValue) {
              console.log('----found porop', prop, ', ', theObject[prop]);
              finalResults.push(theObject);
            }
          }
          if (theObject[prop] instanceof Object || theObject[prop] instanceof Array){
            getObject(theObject[prop]);
          }
        }
      }
    }
  }

  getObject(obj);

}

它所做的是在obj中查找属性名称和值与targetProptargetValue匹配的任何对象,并将其推送到finalResults数组。下面是可供使用的jsfiddle:https://jsfiddle.net/alexQch/5u6q2ybc/

hsvhsicv

hsvhsicv7#

为此,我创建了库:https://github.com/dominik791/obj-traverse

您可以这样使用findFirst()方法:

var foundObject = findFirst(rootObject, 'options', { 'id': '1' });

现在foundObject变量存储了对您正在查找的对象的引用。

hgb9j2n6

hgb9j2n68#

另一种递归解决方案,适用于数组/列表和对象,或两者的混合:

function deepSearchByKey(object, originalKey, matches = []) {

    if(object != null) {
        if(Array.isArray(object)) {
            for(let arrayItem of object) {
                deepSearchByKey(arrayItem, originalKey, matches);
            }
        } else if(typeof object == 'object') {

            for(let key of Object.keys(object)) {
                if(key == originalKey) {
                    matches.push(object);
                } else {
                    deepSearchByKey(object[key], originalKey, matches);
                }

            }

        }
    }

    return matches;
}

用法:

let result = deepSearchByKey(arrayOrObject, 'key'); // returns an array with the objects containing the key
cbwuti44

cbwuti449#

如果您对整个ES6感兴趣,您可以使用

const findByKey = (obj, kee) => {
    if (kee in obj) return obj[kee];
    for(n of Object.values(obj).filter(Boolean).filter(v => typeof v === 'object')) {
        let found = findByKey(n, kee)
        if (found) return found
    }
}

const findByProperty = (obj, predicate) => {
    if (predicate(obj)) return obj
    for(n of Object.values(obj).filter(Boolean).filter(v => typeof v === 'object')) {
        let found = findByProperty(n, predicate)
        if (found) return found
    }
}

按值查找将略有不同

let findByValue = (o, val) => {
    if (o === val) return o;
    if (o === NaN || o === Infinity || !o || typeof o !== 'object') return;
    if (Object.values(o).includes(val)) return o;
    for (n of Object.values(o)) {
        const found = findByValue(n, val)
        if (found) return n
    }
}

那么它们就可以像这样使用

const arry = [{ foo: 0 }, null, { bar: [{ baz: { nutherKey: undefined, needle: "gotcha!" } }]}]
const obj = { alice: Infinity, bob: NaN, charlie: "string", david: true, ebert: arry }

findByKey(obj, 'needle')
// 'gotcha!'

findByProperty(obj, val => val.needle === 'gotcha!')
// { nutherKey: undefined, needle: "gotcha!" }

findByValue(obj, 'gotcha!')
// { nutherKey: undefined, needle: "gotcha!" }
x6492ojm

x6492ojm10#

我们使用object-scan进行数据处理。它在概念上非常简单,但允许很多很酷的东西。以下是您将如何解决您的特定问题

// const objectScan = require('object-scan');

const find = (id, input) => objectScan(['**'], {
  abort: true,
  rtn: 'value',
  filterFn: ({ value }) => value.id === id
})(input);

const data = [{ 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: {} }] }] }] }];

console.log(find('1', data));
// => { image: 'http://www.asdasd.com', title: 'Sandals', id: '1', content: {} }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>
px9o7tmv

px9o7tmv11#

您可以在递归函数中使用javascript some函数。有些方法的优点是,一旦孩子被发现,就可以停止循环。不要使用在大数据中速度较慢的Map。

const findChild = (array, id) => {
  let result;
  array.some(
    (child) =>
      (child.id === id && (result = child)) ||
      (result = findChild(child.options || [], id))
  );
  return result;
};

findNode(array, 1)
tzdcorbm

tzdcorbm12#

@Iulian Pinzaru的答案几乎就是我需要的,但如果您的对象有任何空值,它就不起作用。这个版本解决了这个问题。

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++) {
    const nextObject = object[Object.keys(object)[i]];
    if (nextObject && typeof nextObject === "object") {
      let o = deepSearch(nextObject, key, predicate)
      if (o != null) return o
    }
  }
  return null
}
ldxq2e6h

ldxq2e6h13#

只要使用递归函数即可。
请参见下面的示例:

const data = [
  {
    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: {},
              }
            ]
          }
        ]
      }
    ]
  }
]

function _find(collection, key, value) {
  for (const o of collection) {
    for (const [k, v] of Object.entries(o)) {
      if (k === key && v === value) {
        return o
      }
      if (Array.isArray(v)) {
        const _o = _find(v, key, value)
        if (_o) {
          return _o
        }
      }
    }
  }
}

console.log(_find(data, 'channel_id', 'dsa2'))
zpqajqem

zpqajqem14#

function getPropFromObj(obj, prop) {
            let valueToFindByKey;
            if (!Array.isArray(obj) && obj !== null && typeof obj === "object") {
              if (obj.hasOwnProperty(prop)) {

                 valueToFindByKey = obj[prop];
               console.log(valueToFindByKey);
              } else {

                let i;
                for (i = 0; i < Object.keys(obj).length; i++) {

                    getPropFromObj(obj[Object.keys(obj)[i]], prop);
                }
              }

            }
            return null;

          }

        const objToInvestigate = {
            employeeInformation: {
              employees: {
                name: "surya",
                age: 27,
                job: "Frontend Developer",
              },
            },
          };
          getPropFromObj(objToInvestigate, "name");

1.检测深度嵌套对象中的键。
1.最后返回检测到的key的值。

42fyovps

42fyovps15#

改进了答案,以考虑对象内的循环引用。它还显示了它到达那里的路径。

在本例中,我正在搜索我知道位于全局对象中某个位置的IFrame:

const objDone = []
var i = 2
function getObject(theObject, k) {
    if (i < 1 || objDone.indexOf(theObject) > -1) return
    objDone.push(theObject)
    var result = null;
    if(theObject instanceof Array) {
        for(var i = 0; i < theObject.length; i++) {
            result = getObject(theObject[i], i);
            if (result) {
                break;
            }   
        }
    }
    else
    {
        for(var prop in theObject) {
            if(prop == 'iframe' && theObject[prop]) {
                i--;
                console.log('iframe', theObject[prop])
                return theObject[prop]
            }
            if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
                result = getObject(theObject[prop], prop);
                if (result) {
                    break;
                }
            } 
        }
    }
    if (result) console.info(k)
    return result;
}

运行以下命令:getObject(reader, 'reader')将显示以下输出和最后的iframe元素:

iframe // (The Dom Element)
_views
views
manager
rendition
book
reader

注意:路径的顺序与reader.book.rendition.manager.views._views.iframe相反

相关问题