Javascript + Filter object of values I have the object with values. I trying to filter based on values.
var data = {
  &quot;map&quot;: {
    &quot;0&quot;: [&quot;abcd&quot;],
    &quot;1&quot;: [&quot;efgh&quot;],
    &quot;2&quot;: [&quot;xyz&quot;],
  }
}

In above object I am trying to filter xyz which are have in array values.
Expecting output:
 { '0': [ 'xyz' ] }

I done the code but I am not sure it's efficient way. Can someone help me this.


const  data = {
  "map": {
    "0": ["abcd"],
    "1": ["efgh"],
    "2": ["xyz"],
    "3": ["abcd", "xyz"],
  }
}

const filtered = Object.keys(data.map)
  .filter((key) =&gt; {
    return data.map[key].includes('xyz');
  })
  .reduce((obj, key, cIndex) =&gt; {
    obj[cIndex] = data.map[key];
    return obj;
  }, {});
  
  console.log('filtered', filtered);
Avoid use dictionary when you need Array
I'm not sure why you would prefer to store your Array-like data in a dictionary. I would suggest use a real Array if you need an Array.
Order of Object.keys
You may read more details about the order of Object.keys return values from this post: Does ES6 introduce a well-defined order of enumeration for object properties? The order of Object.keys is defined in ES2020. It may not work as you want in older environments.
Anyway, relay on the order of Object.keys don't seems to be a good idea to me. You may always sort the keys after Object.keys if you want though.
Use Object.assign to convert to / from Array
When you need an Array, use an Array. You can try Object.assign which convert your dictionary into Array and vice versa. (But this only applied to &quot;when you cannot change the interface due to any reason&quot;).
function filterData(data, value) {
    const arrayData = Object.assign([], data.map);
    const filteredArrayData = arrayData.filter(list =&gt; list.includes(value));
    const result = Object.assign({}, filteredArrayData);
    return result;
}