【问题标题】:Search a value inside complex object在复杂对象中搜索值
【发布时间】:2015-12-10 16:21:42
【问题描述】:

我有一个具有嵌套值的复杂对象。值可以是字符串、数组、对象数组或null 对象。像这样的:

{
foo:'a',
bar:'b',
otherthings : [{yep:'0',yuk:'yoyo0'},{yep:'1',yuk:'yoyo1'}],
foobar : 'yup',
value: null
}

检查对象中某处是否存在值(例如yoyo1)的最快方法是什么?有 Javascript 内置函数吗?

【问题讨论】:

  • Javascript find json value 的可能重复项
  • 有 Javascript 内置函数吗? 没有,必须自己实现。递归是你的朋友。
  • 不,javascript没有内置功能,但您可以使用简单的for...in循环并手动检查所有内容
  • 您可以遍历每个对象键/值,或者如果您只想知道值是否存在,您可以使用 JSON.stringify 将对象转换为文本并搜索 ":'value '" 你可以在字符串上使用正则表达式
  • JSON.stringify + RegEx 进行内部递归,因此性能相同。下面有一个使用indexOf 的答案,需要遍历所有字符串。性能将相同或几乎非常相似。你能做的最好的就是你认为更易读、更容易写的东西。

标签: javascript


【解决方案1】:

一些简短的迭代:

var data = {
    foo: 'a',
    bar: 'b',
    otherthings: [{ yep: '0', yuk: 'yoyo0' }, { yep: '1', yuk: 'yoyo1' }],
    foobar: 'yup',
    value: null
};

function findInObject(o, f) {
    return Object.keys(o).some(function (a) {
        if (Array.isArray(o[a]) || typeof o[a] === 'object' && o[a] !== null) {
            return findInObject(o[a], f);
        } 
        return o[a] === f;
    });
}

document.write(findInObject(data, 'yoyo1') + '<br>');
document.write(findInObject(data, 'yoyo2') + '<br>');
document.write(findInObject(data, null) + '<br>');

【讨论】:

  • Wie machst Du das bloß immer? :-) +1
【解决方案2】:

正则表达式解决方案

var myObject = {
    foo: 'a',
    bar: 'b',
    otherthings: [{
        yep: '0',
        yuk: 'yoyo0'
    }, {
        yep: '1',
        yuk: 'yoyo1'
    }],
    foobar: 'yup',
    value: null
};

var myStringObject = JSON.stringify(myObject);
var matches = myStringObject.match('yep'); //replace yep with your search query

demo

【讨论】:

  • 如果 json 具有属性 yep,这也将匹配,不一定是值 'yep'。
  • 我完全同意你的看法,因此查询需要正确
  • 好吧听起来不错。这样我也可以搜索像'y''yo' 这样的子字符串。我看到的唯一问题是,当我搜索 'nu''ul''null' 之类的子字符串时,因为我还包含来自字符串化对象的 null 匹配
【解决方案3】:
var jsonStr = JSON.stringify(myJSON);
return jsonStr.indexOf(':"yolo1"') !== -1;

这仅在您想知道它是否存在(而不是它在哪里)时才有效。它也可能不是性能最好的。

【讨论】:

    【解决方案4】:

    另一种解决方案:

     function findInObject(obj, comparedObj){
         return Object.keys(obj).some(function(key){
             var value = obj[key];
    
             if (!value) {
               return false;
             }
    
             if (typeof value === "string") {
                return value === comparedObj;
             }
    
             if (value instanceof Array) {
                return value.some(function(e){ 
                    return (typeof value === "string" && e === comparedObj) || 
                           findInObject(e, comparedObj);
                });
             }
    
             return findInObject(value, comparedObj);
        });  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 2023-01-27
      • 1970-01-01
      • 2011-11-26
      • 2012-01-20
      相关资源
      最近更新 更多