admin管理员组

文章数量:1401923

I have an array something like this:

data: [
  [
    {}, {} ... //multiple objects
  ]
]

How do I remove those second square brackets? I want it to be changed from [[{}]] to [{}].

I have an array something like this:

data: [
  [
    {}, {} ... //multiple objects
  ]
]

How do I remove those second square brackets? I want it to be changed from [[{}]] to [{}].

Share Improve this question edited Oct 20, 2020 at 7:00 Derek Wang 10.2k4 gold badges19 silver badges40 bronze badges asked Mar 8, 2018 at 8:52 Vinay SinghVinay Singh 4832 gold badges9 silver badges17 bronze badges 5
  • 3 data = data[0] ... quite simple if you would have looked around a bit though. – trincot Commented Mar 8, 2018 at 8:54
  • A square bracket within an array would signfy that there is an array within the array. So, you need to loop through the inner array and push individual objects to a flat array – Anirudh Modi Commented Mar 8, 2018 at 8:54
  • var arr = data[0] .. whats so big in it? – izengod Commented Mar 8, 2018 at 8:54
  • 4 The downvotes indicate that we think you did not research this enough before asking the question. – trincot Commented Mar 8, 2018 at 8:54
  • This seems to be a task for a programming class. The teacher probably saw your code and told you to remove those brackets. Nothing to worry aboit, you can just delete them using the backspace key. – Tamas Hegedus Commented Mar 8, 2018 at 8:58
Add a ment  | 

2 Answers 2

Reset to default 5

Extract first item of your array

var data = [
  [
    {id: 1},
    {id: 2}
  ]
]
console.log(data);

var newData = data[0];
console.log(newData);

You can use Array.flat() to flatten sub-arrays:

const data = [
  [
    {id: 1},
    {id: 2}
  ],
  [
    {id: 3},
    {id: 4}
  ]
];

const newData = data.flat();
console.log(newData);

If Array.flat() is not supported, you can spread the array into Array.concat():

const data = [
  [
    {id: 1},
    {id: 2}
  ],
  [
    {id: 3},
    {id: 4}
  ]
];

const newData = [].concat(...data);
console.log(newData);

本文标签: How to remove second square brackets from an array using JavaScriptStack Overflow