简体   繁体   English

如何将对象数组转换为 object 的 object

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

相关问题 如何将JavaScript对象数组转换为单个对象? - How do you convert an array of JavaScript objects to a single object? 如何将{“name”:“myName”,“value”:“myValue”}对象的数组转换为“myName”的对象:JavaScript中的“myValue”对? - How do you convert an array of {“name”:“myName”,“value”:“myValue”} objects into an object of “myName”:“myValue” pairs in JavaScript? 如何根据某个属性将对象数组转换为 arrays 的 object? - How do you convert array of objects to object of arrays based on a certain property? 如何将 javascript object 与 arrays 转换为具有相应名称和值的对象数组? - how do you convert javascript object with arrays in to array of objects with corresponding name and value? 如何将一个对象转换为一个对象数组? - How to convert an object into an array of objects? 如何将对象转换为对象数组 - How to convert an object to array of objects 如何将对象转换为对象数组 - How to convert object into array of objects 您如何 map object 中的对象数组? - How do you map an array of objects within an object? 如何遍历对象数组以创建新的 object? - How do you iterate over an array of objects to create a new object? 如何将JSON对象转换为Javascript数组? - How do you convert a JSON object to a Javascript array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM