How to check if array has nested property with def

2019-07-29 05:38发布

问题:

I have an array of complicated objects and arrays in javascript such as:

var array = [
    { "simpleProp": "some value" },
    { "booleanProp": false },
    {
        "arrayProp": [
            { "prop1": "value1" },
            {
                "prop2": {
                    "prop22": "value22",
                    "prop23": "value23"
                } 
            },
            { "prop3": "value3" },
            { "booleanProp": true }
        ]
    }
];

I have to know if there is a property with defined value in my array, such as:

   function some(array, property, value) {
        //some logic here
       // return boolean
    };

That is, for my source array the result of this:

var result = some(array, "booleanProp", true) - must be TRUE.

I tried to use lodash function _.some(), but it returns false for my array, it appears _.some() can't find deeply nested properties.

It would be very cool if the function may support complicated object as source, not only array.

I'd appreciate any help, thanks.

回答1:

You could use an iterative and recursive approach by checking the actual object and if the value is an object iterate the object's keys.

function some(object, property, value) {
    return object[property] === value || Object.keys(object).some(function (k) {
         return object[k] && typeof object[k] === 'object' && some(object[k], property, value);
    });
}

var data = [{ simpleProp: "some value" }, { booleanProp: false }, { arrayProp: [{ prop1: "value1" }, { prop2: { prop22: "value22", prop23: "value23" } }, { prop3: "value3" }, { booleanProp: true }] }];

console.log(some(data, 'booleanProp', true)); // true
console.log(some(data, 'foo', 42));           // false