在包含嵌套对象和数组

时间:2017-05-13 05:21:20

标签: javascript

我有以下对象和值 -

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

现在我有一个值 - “空格”,现在我想检查任何级别的对象中是否存在“空格”。如果存在“spaces”,则函数应返回true。

我尝试了递归方式,但我应该如何处理数组呢?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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"));