简体   繁体   English

在 JS 中重构对象数组,使键值对匹配

[英]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.

相关问题 如何将字符串数组转换为对象,以便可以将这些对象拆分为键值对? - How to covert an array of strings into objects so that I can split those objects into key value pairs? 将键/值对数组转换为对象数组 - Transform an array of key/value pairs into array of objects 查找 function 以匹配两个不同 arrays 对象中的相同 ID,并将键/值对插入对象数组之一 - A lookup function to match the same IDs in two different arrays of objects and inserting key/value pairs into one of the array of objects 以对象作为键值对中的值构建数组 - Build Array with Objects as the value in key value pairs Restructure object array with key value pairs in Javascript and output or emit it to save it with mongoose and MongoDB? - Restructure object array with key value pairs in Javascript and output or emit it to save it with mongoose and MongoDB? 按键值对过滤数组中的对象 - Filter objects in array by key-value pairs 在CoffeeScript中将对象数组映射到键/值对 - Mapping an array of objects to key/value pairs in CoffeeScript 如何将对象数组转换为键值对 - How to convert an array of objects into key value pairs JS匹配包含嵌套对象和嵌套数组的数组中的键值 - JS match key value in array containing nested objects and nested arrays 将JS Array中的键值对减少为object - reduce key value pairs in JS Array to object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM