[英]Restructure an array of objects in JS so key and value pairs match
I have an array with objects like this我有一个包含这样的对象的数组
[
{name: 'Donegal', code: 'DL'},
{name: 'Dublin', code: 'DUB'},
{name: 'Meath', code: 'MH'}
]
How do I restructure it so it looks like this我如何重组它,使其看起来像这样
[
{Donegal: 'Donegal'},
{Dublin: 'Dublin'},
{Meath: 'Meath'}
]
**** EDIT **** **** 编辑 ****
Apologies, but after receiving feedback, I looked at my question again and realized that I wrote the desired object incorrectly, apologies for that.抱歉,但在收到反馈后,我再次查看了我的问题,发现我写错了所需的 object,对此深表歉意。 Regardless, the question has been answered (Thank you everyone for your comments and answers).
无论如何,问题已经得到解答(感谢大家的评论和回答)。 For the record, here is the desired output
作为记录,这里是所需的 output
[
{
Donegal: 'Donegal',
Dublin: 'Dublin',
Meath: 'Meath'
}
]
The structure you are targeting looks wrong: having an array with little objects that have one dynamic property, kills any benefit you would have from using object keys.您定位的结构看起来是错误的:拥有一个包含具有一个动态属性的小对象的数组,会破坏您使用 object 键所带来的任何好处。
Instead go for one object (not an array):而不是 go一个object (不是数组):
let input = [ {name: 'Donegal', code: 'DL'}, {name: 'Dublin', code: 'DUB'}, {name: 'Meath', code: 'MH'} ]; let output = Object.fromEntries( input.map(({name}) => [name, name]) ); console.log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.