0

I have a dynamic array var arr = ["key1","key2","key3"] i want to filter an array of objects with this array,for example,

var obj = [{"key1":{"key2":{"key3":5}}},{"key1":{"key2":{"key3":7}}},{"key1":{"key2":{"key3":8}}}] 

with "key3" equals to 5. How can I achieve this with vanilla javascript?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
vishnu v
  • 313
  • 4
  • 10

1 Answers1

1

You could reduce the keys with the object and return the value for checking.

var getValue = (keys, object) => keys.reduce((o, k) => o[k], object),
    keys = ["key1", "key2", "key3"],
    array = [{ key1: { key2: { key3: 5 } } }, { key1: { key2: { key3: 7 } } }, { key1: { key2: { key3: 8 } } }],
    result = array.filter(o => getValue(keys, o) === 5);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392