Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
86
rated 0 times [  91] [ 5]  / answers: 1 / hits: 33039  / 5 Years ago, sun, february 24, 2019, 12:00:00

How would I find all values by specific key in a deep nested object?


For example, if I have an object like this:


const myObj = {
id: 1,
children: [
{
id: 2,
children: [
{
id: 3
}
]
},
{
id: 4,
children: [
{
id: 5,
children: [
{
id: 6,
children: [
{
id: 7,
}
]
}
]
}
]
},
]
}

How would I get an array of all values throughout all nests of this obj by the key of id.


Note: children is a consistent name, and id's won't exist outside of a children object.


So from the obj, I would like to produce an array like this:


const idArray = [1, 2, 3, 4, 5, 6, 7]

More From » arrays

 Answers
23

You could make a recursive function like this:



idArray = []

function func(obj) {
idArray.push(obj.id)
if (!obj.children) {
return
}

obj.children.forEach(child => func(child))
}


Snippet for your sample:





const myObj = {
id: 1,
children: [{
id: 2,
children: [{
id: 3
}]
},
{
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: [{
id: 7,
}]
}]
}]
},
]
}

idArray = []

function func(obj) {
idArray.push(obj.id)
if (!obj.children) {
return
}

obj.children.forEach(child => func(child))
}

func(myObj)
console.log(idArray)




[#52543] Tuesday, February 19, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryley

Total Points: 118
Total Questions: 81
Total Answers: 102

Location: Kazakhstan
Member since Thu, Dec 23, 2021
3 Years ago
ryley questions
Thu, Sep 2, 21, 00:00, 3 Years ago
Wed, Feb 12, 20, 00:00, 4 Years ago
Wed, Oct 30, 19, 00:00, 5 Years ago
;