Home > Blockchain >  Remove the first bracket from nested array
Remove the first bracket from nested array

Time:10-28

I have an array as follow:

let data =[
  [
    {
      "Id": "110d611c-54e4-4593-a835-def0f34ed882",
      "duration": 30,
      "name": "burger",
      "price": 10,
      
    }
  ],
  [
    {
      "Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
      "duration": 10,
      "name": "Cake",
      "price": 5,
      
    }
  ]
]

I am trying to remove the first bracket to be like this:

let data =

     [
        {
          "Id": "110d611c-54e4-4593-a835-def0f34ed882",
          "duration": 30,
          "name": "burger",
          "price": 10,
          
        }
      ],
      [
        {
          "Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
          "duration": 10,
          "name": "Cake",
          "price": 5,
          
        }
      ]

I have trying many solutions, the most common one i have tried is using this way:

let newData = data[0]

but the result always giving me the first nested array something like this:

  [
    {
      "Id": "110d611c-54e4-4593-a835-def0f34ed882", 
      "duration": 30, 
      "name": "burger", 
      "price": 10
    }
  ]

I tried to convert it to string using JSON.stringify() then remove the bracket by doing

JSON.stringify(data).substring(1, JSON.stringify(data).length - 1);

But then when i parse it i get this error:

SyntaxError: JSON Parse error: Unable to parse JSON string

I am really stuck on what the best way to accomplish it. thanks in advance.

CodePudding user response:

You want the first element of each nested array, not the first element of the outer array. So use map().

let data = [
  [{
    "Id": "110d611c-54e4-4593-a835-def0f34ed882",
    "duration": 30,
    "name": "burger",
    "price": 10,

  }],
  [{
    "Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
    "duration": 10,
    "name": "Cake",
    "price": 5,

  }]
];

let newData = data.map(el => el[0]);
console.log(newData);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Removing the external bracket will result in an invalid javascript object.

To obtain a single array with all the objects you can use flatMap

data.flatMap(x => x)

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap

CodePudding user response:

The result that you want is not valid, instead you can get array of object using flat as:

data.flat()

let data = [
  [
    {
      Id: "110d611c-54e4-4593-a835-def0f34ed882",
      duration: 30,
      name: "burger",
      price: 10,
    },
  ],
  [
    {
      Id: "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
      duration: 10,
      name: "Cake",
      price: 5,
    },
  ],
];

const result = data.flat();
console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related