Skip to content Skip to sidebar Skip to footer

How To Check If Array Has Nested Property With Defined Value

I have an array of complicated objects and arrays in javascript such as: var array = [ { 'simpleProp': 'some value' }, { 'booleanProp': false }, { 'arrayProp':

Solution 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.

functionsome(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)); // trueconsole.log(some(data, 'foo', 42));           // false

Solution 2:

Above Solution is great but it is not working for Array. So I've Modified it little bit and now it is working for both Arrays & normal properties. Even In Arrays element's placement can be anything.

constdata = {
    "names": [
      {
        "name": {
          'homename': 'Raju',
          'academisName': 'Rajpal',
          'callingName': ['Raj', 'Rajpal', 'Raju']
        },
        "defaultName": "Raj"
      }]
  }

Code for Array:

constsome = (object, property, value) => {
  return _.isArray(value) && _.isEqual(_.sortBy(object[property]), _.sortBy(value)) || object[property] === value || Object.keys(object).some(function (k) {
    returnobject[k] && typeofobject[k] === 'object' && some(object[k], property, value);
  });
}

const data = {
  "names": [{
    "name": {
      'homename': 'Raju',
      'academisName': 'Rajpal',
      'callingName': ['Raj', 'Rajpal', 'Raju']
    },
    "defaultName": "Raj"
  }]
}
constsome = (object, property, value) => {
  return _.isArray(value) && _.isEqual(_.sortBy(object[property]), _.sortBy(value)) || object[property] === value || Object.keys(object).some(function(k) {
    return object[k] && typeof object[k] === 'object' && some(object[k], property, value);
  });
}
console.log('Result 1', some(data, 'callingName', ["Raj", "Rajpal", "Raju"]));
console.log('Result 2', some(data, 'callingName', ["Rajpal", "Raj", "Raju"]));
<scriptsrc="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.js"></script>

Note: that value.sort() will mutate the arrays so I've used _.sortBy(value), same for object[property]

 console.log(some(data, 'callingName',  ["Raj", "Rajpal", "Raju"]));
 console.log(some(data, 'callingName', ["Rajpal", "Raj", "Raju"]));

Post a Comment for "How To Check If Array Has Nested Property With Defined Value"