i wanna return correctly children's object. how can i?

function Ha8(arr, id) {
  let result = [];
  for(let i = 0;  i < arr.length; i++) {
    if(Array.isArray(arr[i].children)) {
     // if it is a array, it going to be run recursive
      result.push(arr[i].children)
    const col = Ha8(result[i], id);
      if(col === id)  {
        // find it in array in array 
        return result
        // then return the id object, 
      } else {
        continue; // still can't find.. go ahead! 
      }  
    } else if (arr[i]['id']===id) {
      return arr[i] // will return valid id object 
  }
  return null // if its none , return null, or parameter id is undefined. 
 }
}

I m write Intended direction. but its not work..
how can i fix ? give me some tip please.

let input = [
  {
    id: 1,
    name: 'johnny',
  },
  {
    id: 2,
    name: 'ingi',
    children: [
      {
        id: 3,
        name: 'johnson',
      },
      {
        id: 5,
        name: 'steve',
        children: [
          {
            id: 6,
            name: 'lisa',
          },
        ],
      },
      {
        id: 11,
      },
    ],
  },
  {
    id: '13',
  },
];

output = Ha8(input, 5);
console.log(output); // --> { id: 5, name: 'steve', children: [{ id: 6, name: 'lisa' }] }

output = Ha8(input, 99);
console.log(output); // --> null

I wanna return like that, but only return ‘null’ ..
need to check children’s id and return children’s object by using recursive.
so i write like that. but i have no idea..
how to return correctly children id’s element?

1 thought on “i wanna return correctly children's object. how can i?”

  1. I will give you an answer using a totally different approach, and using the magic of the JSON.stringify() method, more specifically the replacer optional parameter, which allows the use of a callback function that can be used as a filter.

    As you can see, it simplifies a lot the final code. It could also be modified to introduce not only an id, but also any key or value, as I did in my final approach.

    const input = [{"id":1,"name":"johnny"},{"id":2,"name":"ingi","children":[{"id":3,"name":"johnson"},{"id":5,"name":"steve","children":[{"id":6,"name":"lisa"}]},{"id":11}]},{"id":"13"}]
    
    const Ha8 = (array, inputKey, inputValue) => {
        let children = null;
        JSON.stringify(array, (key, value) => {
            if (value && value[inputKey] === inputValue) {
                children = value;
            }
            return value;
        });
        return children;
    };
    
    console.log(Ha8(input, 'id', 5))
    Reply

Leave a Comment