简体   繁体   English

在单个对象中转换对象数组

[英]Convert an array of Objects in individual objects

I have the following example array of objects我有以下示例对象数组

[ 
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }
];

that I would like to only have individual objects like:我只想拥有单个对象,例如:

{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }

and store them in useState like so并将它们存储在 useState 像这样

array.map((object)=>{
setObjects({...object})
 })

but when do但是什么时候做

console log(objects)

it only outputs one object not all of them它只输出一个 object 而不是全部

You are overriding your object after each iteration.您将在每次迭代后覆盖您的 object。 One way is to make a new object if you are sure the key will be unique then use this one.一种方法是制作一个新的 object 如果您确定密钥是唯一的,然后使用这个。

array.map((object)=>{
 setObjects((prevState) => ({...prevState, [object.key]: object }) )
})

It will produce the output like this.它将像这样产生 output。

{
  11 : { key : '11', value : '1100', $$hashKey : '00X' },
  12 : { key : '22', value : '2200', $$hashKey : '018' }
}

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

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