[英]How do you convert an array of objects into an object of object
I am having trouble converting an array of objects into an object of objects for my job.对于我的工作,我无法将对象数组转换为 object 对象。 The company API is expecting the data in this format.
API 公司期待这种格式的数据。 Any help would be appreciated.
任何帮助,将不胜感激。 Here is an example
这是一个例子
Original原来的
const array = [
{
type: 'ITEM',
info: {
item_id: 'house'
}
},
{
type: 'ITEM',
info: {
item_id: 'house'
}
}
]
Final最后
const array = {
{
type: 'ITEM',
info: {
item_id: 'house'
}
},
{
type: 'ITEM',
info: {
item_id: 'house'
}
}
}
You have to use key/value pairs for object elements, but you can create an object from this array like this:您必须为 object 元素使用键/值对,但您可以从该数组创建 object,如下所示:
const array = [ { type: 'ITEM', info: { item_id: 'house' } }, { type: 'ITEM', info: { item_id: 'house' } } ] let result = {} array.forEach((el, idx) => { result['data_' + idx] = el }) console.log(result)
Your Object will need keys.您的 Object 将需要密钥。 An Object in Javascript is always { key:value, ...} (key-value pairs).
Javascript 中的 Object 始终为 { key:value, ...}(键值对)。
Therefor you will need to create these:因此,您将需要创建这些:
const array = [ { type: 'ITEM', info: { item_id: 'house' } }, { type: 'ITEM', info: { item_id: 'house' } } ] const obj = array.reduce((o,e,i) => { return {...o, ['item_'+i]: e }}, {}); console.log(obj);
change 'items_' to whatever suits your purpose.将“items_”更改为适合您目的的任何内容。 If possible I'd suggest using an array here though.
如果可能的话,我建议在这里使用一个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.