简体   繁体   中英

Javscript: remove curly brackets from objects(with keys and values) in an array

I have an array like this(data retrieved from mySql and json_encode() in PHP, coming back as a json object(totally 19 elements in this array, and all the objects in different order in the element)):

const array=[
  [{"name":"jason"},{"age":16},{"location":"London"}],
  [{"age":24},{"location":"Tokyo"},{"name":"amy"}]
]

How to convert it to an array like this, removing curly brackets?

const array=[
  {"name":"jason","age":16,"location":"London"},
  {"name":"amy","age":24,"location":"Tokyo"}
]

I have tried to convert to string, then

String.replace(/[{}]/g, '');

But what's next? I got stuck at converting back to array again.

And the other question is:For an array like this, when to access the keys and values, is it neccesary to re-structure the keys and values to make them the same order in each element, otherwise it doesn't look nice and is not easy to access?

[
  [{"name":"jason"},{"age":16},{"location":"London"}],
  [{"age":24},{"location":"Tokyo"},{"name":"amy"}]
]

Any tips on how to think about flattening this will be much appreciated!

The .replace() method is used for strings, not objects/arrays. Instead, you can merge the objects within each inner array together by using .map() to trasform each array, and Object.assign() to merge the given array of objects.

See example below:

 const array = [ [{"name":"jason"},{"age":16},{"location":"London"}], [{"age":24},{"location":"Tokyo"},{"name":"amy"}] ]; const res = array.map(inner => Object.assign({}, ...inner)); console.log(res);

The order of your (string) keys in the resulting objects will appear in the order that they're inserted, so as your object order is different for each inner array, your resulting object's key-ordering will also be different once they're merged. However, this shouldn't matter too much as relying on object key ordering is often not the best idea, and can be done more reliably using other methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM