javascriptjsonecmascript-6ecmascript-2016

Javascript-searching for a string in the properties of an array of objects


I have an array of JSON objects. Given a search string, I want to filter the array for only those objects which have that string as a substring of one of their properties. How do I do this efficiently?


Solution

  • Assuming you want to find the substring in the property value, you can use the following code:

    const arr = [
      {a:'abc', b:'efg', c:'hij'},
      {a:'abc', b:'efg', c:'hij'},
      {a:'123', b:'456', c:'789'},
    ];
    
    const search = 'a';
    
    const res = arr.filter(obj => Object.values(obj).some(val => val.includes(search)));
    
    console.log(res);

    If you want to search the property name, use Object.keys instead of Object.values.

    Please note that Object.values is a feature of ES2017.