Home > Software engineering >  Remove array bracket before pushing to an array
Remove array bracket before pushing to an array

Time:04-28

[
  [
    {
      "id": "5d52eaa88c31223a0ea27df7",
      catalogues: [Array]
    }
  ],
  [
    {
      "id": "5d52f17a8c31223a0ea27e38",
      catalogues: [Array]
    }
  ],
  [
    {
      "id": "5d52f17a8c31223a0ea27e32",
      catalogues: [Array]
    }
  ],
  [
    {
      "id": "5d52f17a8c31223a0ea27e31",
      catalogues: [Array]
    }
  ]
]

Make a single array before pushing it to another array containing a JSON object. Can I make it as a json object by removing square bracket before pushing to a array.

CodePudding user response:

You can use flat.

const myArray = [
      [
        {
          id: '5d52eaa88c31223a0ea27df7',
          catalogues: [Array]
        }
      ],
      [
        {
          id: '5d52f17a8c31223a0ea27e38',
          catalogues: [Array]
        }
      ],
    [
        {
          id: '5d52f17a8c31223a0ea27e32',
          catalogues: [Array]
        }
      ],
[
    {
      id: '5d52f17a8c31223a0ea27e31',
      catalogues: [Array]
    }
  ]
    ]
    
console.log(myArray.flat());

CodePudding user response:

Your object is much larger than with [Array] standing for [...] - several elements. For the purpose of the demo I have replaced every occurrence of [Array] with [].

Use the JSON.stringify to convert the whole data into a JSON string as follows - no need to remove any square brackets:

const input = [ [ { id: '5d52eaa88c31223a0ea27df7', catalogues: [] } ], [ { id: '5d52f17a8c31223a0ea27e38', catalogues: [] } ], [ { id: '5d52f17a8c31223a0ea27e32', catalogues: [] } ], [ { id: '5d52f17a8c31223a0ea27e31', catalogues: [] } ] ],

      output = JSON.stringify(input);

console.log( output );

  • Related