Home > Blockchain >  How can i convert multiple arrays to one array in javascript
How can i convert multiple arrays to one array in javascript

Time:06-02

I have this multiple array and i want to convert it to one array with javascript codes and get data from it with flatMap:

    [
        {
      id: '46892319372',
      user_name: 'testerOne',
      identifier: '20202'
    }
]
[
    {
      id: '15243879678',
      user_name: 'testerTwo',
      identifier: '20201'
    }
]
[
    {
      id: '02857428679',
      user_name: 'testerThree',
      identifier: '20203'
    }
]
[
    {
      id: '65284759703',
      user_name: 'testerFour',
      identifier: '20204'
    }
]

i want to convert this multiple arrays to just one array like this with javascript:

[
        {
      id: '46892319372',
      user_name: 'testerOne',
      identifier: '20202'
    },
    {
      id: '15243879678',
      user_name: 'testerTwo',
      identifier: '20201'
    },
    {
      id: '02857428679',
      user_name: 'testerThree',
      identifier: '20203'
    },
    {
      id: '65284759703',
      user_name: 'testerFour',
      identifier: '20204'
    }
]

CodePudding user response:

What you have here is not a multiple array (an array of arrays), but actually multiple arrays. Not sure how you got here but I am assuming you didn't create these, as the solution would be to just be to wrap these in an array and separate each array with a comma, then anything you do to flatten it will work.

Sorry if this is just too rudimentary an answer for now.

Did you create this (can you easily edit the structure) or were these returned to you?

CodePudding user response:

Im not sure if this is what youre after but.. this only works with arrays that contain object literals.

let array1 = [{
    id: '46892319372',
    user_name: 'testerOne',
    identifier: '20202'
  }],
  array2 = [{
      id: '15243879678',
      user_name: 'testerTwo',
      identifier: '20201'
    },
    {
      id: '15243879678',
      user_name: 'testerTwo',
      identifier: '20201'
    }
  ],
  array3 = [{
    id: '02857428679',
    user_name: 'testerThree',
    identifier: '20203'
  }],
  array4 = [{
    id: '65284759703',
    user_name: 'testerFour',
    identifier: '20204'
  }];

function mergeArrays() {
  let array = [];
  for (let i = 0; i < arguments.length; i  ) {
    if (arguments[i].constructor !== Array) continue;
    for (let index = 0; index < arguments[i].length; index  ) {
      if (arguments[i][index].constructor !== Object) continue;
      array.push(arguments[i][index]);
    }
  }
  return array;
}

const mergedArray = mergeArrays(array1, array2, array3, array4)
console.log(mergedArray)

  • Related