Skip to content
Advertisement

How do I recursively use Array.prototype.find() while returning a single object?

The bigger problem I am trying to solve is, given this data:

JavaScript

I want to make a function findById(data, id) that returns { id: id }. For example, findById(data, 8) should return { id: 8 }, and findById(data, 4) should return { id: 4, children: [...] }.

To implement this, I used Array.prototype.find recursively, but ran into trouble when the return keeps mashing the objects together. My implementation returns the path to the specific object.

For example, when I used findById(data, 8), it returns the path to { id: 8 }:

JavaScript

Instead I would like it to simply return

JavaScript

Implementation (Node.js v4.0.0)

jsfiddle

JavaScript

Advertisement

Answer

I would just use a regular loop and recursive style search:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement