2017-05-13 196 views
-2

我有以下對象和值 -查找對象的值包含嵌套對象和數組

{ 
    location:"xyz", 
    title:"abc", 
    company: { 
     address:"address can have spaces", 
     name:"name" 
    }, 
    array-key :[ 
     { skill : "skill1"}, 
     { skill : "skill2"}, 
     { skill : "skill3"} 
    ], 
    description :"brief description" 
} 

,現在我有一個價值 - 「空間」,現在我要檢查,如果「空間」存在於任何級別的對象中。如果「空格」存在,函數應該返回true。

我嘗試了遞歸的方式,但我應該如何處理數組?

回答

2

在對象上遞歸迭代的一個有用技巧是使用replacer參數JSON.stringify

function findString(obj, regexp) { 
    let found = false; 

    JSON.stringify(obj, (k, v) => { 
    if (found || typeof v === 'string' && regexp.test(v)) found = true; 
    else return v; 
    }); 

    return found; 
} 
0

只是爲了完整性與迭代各級遞歸和檢查值strict或作爲字符串,並將String#indexOf

function check(object, value) { 
 
    return Object.keys(object).some(function (key) { 
 
     if (object[key] && typeof object[key] === 'object') { 
 
      return check(object[key], value); 
 
     } 
 
     return object[key] === value || object[key].toString().indexOf(value) + 1; 
 
    }); 
 
} 
 

 
var data = { location: "xyz", title: "abc", company: { address: "address can have spaces", name: "name" }, arrayKey: [{ skill: "skill1" }, { skill: "skill2" }, { skill: "skill3" }], description: "brief description" }; 
 

 
console.log(check(data, "spaces")); 
 
console.log(check(data, "foo"));