JavaScript / Set Increment index from 0

Viewed 196

I have a problem with setting always unique index, incrementing by one.

I have an array like this.

const parentArr = [
  {
    name: 'first parent array',
    childArray: [
      {
        name: '1 / first child'
      },
      {
        name: '1 / second child'
      }
    ]
  },
    {
    name: 'second parent array',
    childArray: [
      {
        name: '2 / first child array'
      },
      {
        name: '2 / second child array'
      }
    ]
  }
]

And I am expecting result like this:

const expectedResult = [
  {
    name: 'first parrent array',
    additionalInfo: [
      {
        index: 0,
        name: '1 - first child'
      },
      {
        index: 1,
        name: '1 - second child'
      }
    ]
  },
   {
    name: 'second parrent array',
    additionalInfo: [
      {
        index: 2,
        name: '2 -first child array'
      },
      {
        index: 3,
        name: '2- second child array'
      }
    ]
  }
]

I want to have index inside additionalInfo, for each item from 0.

I tried like this, but I got wrong index number

  return parentArr.map((parent) => {
    return {
      name: parent.name,
      additionalData: parent.childArray.map((child, index) => ({
        name: child.name
        index: index   // I'M STUCK ON THIS LINE
      })),
    };
  });
2 Answers

You have to manage the index of children independently from the loop. so what about this?

let i = 0;

return parentArr.map((parent) => {
  return {
    name: parent.name,
    additionalData: parent.childArray.map((child) => ({
      name: child.name
      index: i++
    })),
  };
});

The index count should live outside of the map as that will reset it on each iteration.

You can abstract this behaviour into a reusable method as shown below.

const parentArr = [
  {
    name: 'first parent array',
    childArray: [
      {
        name: '1 / first child'
      },
      {
        name: '1 / second child'
      }
    ]
  },
    {
    name: 'second parent array',
    childArray: [
      {
        name: '2 / first child array'
      },
      {
        name: '2 / second child array'
      }
    ]
  }
];


const transformArray = root => {
  let i = 0;
  return root.map(({ name, childArray }) => ({
    name,
    additionalData: childArray.map(({ name }) => ({
      index: i++,
      name
    }))
  }));
};

console.log(transformArray(parentArr));

Related