N
N
Neuro2019-12-05 22:17:16
JavaScript
Neuro, 2019-12-05 22:17:16

How to find an object with a property that has a certain value in a structure with unknown nesting?

It is necessary to find and get an object in which one of the properties will be equal to the search string.

For example, there is an array:

let arrayData = [
    {
        value: 'test',
        newArray: [
            {
                value: 'zero',
                newArray: [
                    {
                        value: 'myValue'
                    }
                ]
            }
        ]
    }
]

and it is necessary to find and return an object in it, whose property will be equal to 'myValue'.
How can I do that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-12-05
@Riveran

function find(obj, val) {
  const values = obj instanceof Object ? Object.values(obj) : [];
  return values.includes(val)
    ? obj
    : values.reduce((found, n) => found || find(n, val), null);
}


const obj = find(arrayData, 'myValue');

A
Alexey, 2019-12-05
@Azperin

Iteration https://learn.javascript.ru/array-iteration

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question