Reduce to the Object?

Asked

Viewed 37 times

1

I’m making a code here, with the following object:

{
    path: 'mtw',
    return: 'hi',
    obj: {
        path: 'he-mele-no-lilo',
        return: 'hi',
        obj: {
            path: 'hawaiian',
            return: 'hi',
            obj: {
                path: 'swiss',
                return: 'hi',
                obj: {
                    path: 'altendorf',
                    return: 'hi',
                }
            }
        }
    }
}

and I need to get in each obj and so catch all the "obj", I tried to do this with reduce:

const res = arr.reduce(function(s: any, a: any){
    console.log(s);
    console.log(a);
    return s;
  }, {});

but it doesn’t get into all the objects, so as I can do, I’m doing something wrong?

Edit: I look for a result like [{path: 'mtw', Return: 'hi'}, {path: 'he-Mele-no-Lilo', Return: 'hi'}, path: 'Hawaiian', Return: 'hi']

  • What is the result you are looking for? You can give an example of what res should be?

  • res should be: [{path: 'mtw', return: 'hi'}, {path: 'he-mele-no-lilo', return: 'hi'}, path: 'hawaiian', return: 'hi']....

1 answer

3


reduce is not the proper method for this. It is not because it will only iterate the number of times the length of the array you are given.

What you need is a recursive function, which calls itself and goes extracting on the internal levels.

Something like that:

const input = {
  path: 'mtw',
  return: 'hi',
  obj: {
    path: 'he-mele-no-lilo',
    return: 'hi',
    obj: {
      path: 'hawaiian',
      return: 'hi',
      obj: {
        path: 'swiss',
        return: 'hi',
        obj: {
          path: 'altendorf',
          return: 'hi',
        }
      }
    }
  }
}

const extractObj = (root) => {
  const res = [{
    path: root.path,
    return: root.return
  }];
  if (root.obj) {
    res.push(...extractObj(root.obj));
  }
  return res;
}

const res = extractObj(input);
console.log(res);

  • 1

    Your answer is correct, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.