Search code examples
javascriptarraysobjectnested-object

Find if key or value exist in the array's nested objects


I have an array of nested objects.

const data = [
  {
    audi: {
      model_Q3: 'Q3',
      model_A3: 'A3'
    }
  },
  {
    mercedes: {
      model_GLA: 'GLA',
      model_GLC: 'GLC'
    }
  }
];

I want a function to return true if the nested object's (audi, mercedes) key or value equals/includes the parameter.

function findCar(parameter) {
  let exists = false;
  data.forEach(cars => {
    Object.entries(cars).map(([_, carValues]) => {
        console.log(carValues)
    });
  }); 
}

findCar('model_Q3') //true;
findCar('model_') //true;
findCar('GLA') // true;
findCar('GL') // true;

Thanks.


Solution

  • Since you're working with a simple object the JSON.stringify method should come quite handy here. It constructs a json string that contains the entire object, and therefore all the keys and values you have in your object. With that string you can extract every key or value by a regex match.

    This is how it may look like:

    function findCar(parameter) {
        const keysAndValues = JSON.stringify(data).match(/"([^"]+)"/g);
        for (let entry of keysAndValues) if (entry.includes(parameter)) return true;
        return false;
    }
    

    The regex here matches for every entry that starts with ", then only characters that are not " and followed by a ".