Ok this is making a lot of assumptions. Also your typos in the starting object were fun to figure out. When did jsFiddle stop highlighting syntax errors? All I got was "unexpected string - line 46" when I tried to run it, and there is no line 46. I had to go to code pen to figure it out.
Code:
const startingObject = [
{id:1, name:"hi"},
{id:2, name:"there"},
{id:3, name:"2+2", subObject: [{id:4, name:"how"},{id:5, name:"to"}]},
{id:6, name:"access"}];
const startingArray = [1,3,5,6];
const result = [];
buildResult(startingObject);
function buildResult(startingObject) {
startingObject.forEach(entry => {
if (startingArray.indexOf(entry.id) > -1) result.push({id:entry.id, name:entry.name});
if (entry.subObject) buildResult(entry.subObject);
});
}
console.log(result);
// result = [{id:1, name:"hi"},
// {id:3, name:"2+2"},
// {id:5, name:"to"},
// {id:6, name:"access"}]
Assumptions are 1) that you meant to start with an array of objects, 2) that the id property is unique (seems safe), 3) that the entries show up in your startingObject in numerical order. If not then it's a somewhat tricker problem, but you can always just do a result.sort() at the end.
If max performance is required you would probably do some things differently.