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?

2
  • what I want to check is obj.filter(e => e["key1"]["key2"]...etc = some_value); but the elements in the array can vary Commented Feb 6, 2020 at 12:28
  • Post at least two example of input and expected output Commented Feb 6, 2020 at 12:39

1 Answer 1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.