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

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


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

最佳答案

一些简短的迭代:


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>');

08-07 18:23