简体   繁体   English

Javscript:从数组中的对象(带有键和值)中删除大括号

[英]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)):我有一个这样的数组(数据从 mySql 和 json_encode() 中检索到 PHP,作为 json 对象返回(此数组中共有 19 个元素,并且所有对象在元素中的顺序不同)):

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. .replace()方法用于字符串,而不是对象/数组。 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.相反,您可以将每个内部数组中的对象合并在一起,方法是使用.map()转换每个数组,并Object.assign()合并给定的对象数组。

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.结果对象中的(字符串)键的顺序将按照它们插入的顺序出现,因此由于每个内部数组的 object 顺序不同,因此合并后结果对象的键顺序也会不同. 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.然而,这应该没有太大关系,因为依赖 object 密钥排序通常不是最好的主意,可以使用其他方法更可靠地完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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