javascript - 从具有自定义键值的对象数组创建对象

标签 javascript arrays object

现在我知道有一些类似的问题,例如 this questionthis question但都没有回答我的问题。

好吧……

假设我有一个 api 调用,我得到这样的响应

[
  {
     amount: 23,
     bill: 47,
     otherData: null,
     title: 'cool title'
  },
  {
     amount: 223,
     bill: 427,
     otherData: null,
     title: 'cooler title'
  },
  {
     amount: 2313,
     bill: 437,
     otherData: null,
     title: 'super cool title'
  },
  {
     amount: 123,
     bill: 147,
     otherData: null,
     title: 'coolest title'
  }
]

有没有一种方法可以从该数组创建一个新对象,并使用该对象中的属性来自定义键名称?所以所需的输出是..

{
  coolTitle: {
     amount: 23,
     bill: 47,
     otherData: null,
     title: 'cool title'
  },
  coolerTitle: {
     amount: 223,
     bill: 427,
     otherData: null,
     title: 'cooler title'
  },
  superCoolTitle: {
     amount: 2313,
     bill: 437,
     otherData: null,
     title: 'super cool title'
  },
  coolestTitle: {
     amount: 123,
     bill: 147,
     otherData: null,
     title: 'coolest title'
  }
}

现在我知道我可以将对象数组转换为像这样的对象..

var result = {};
for (var i=0; i<array.length; i++) {
  result[array[i].key] = array[i].value;
}

但我不知道如何从每个对象中获取标题,使用驼峰式命名,然后创建自定义键和对象

我什至不确定这样的事情是否可能,任何帮助将不胜感激

谢谢

最佳答案

要获取属性名称,请提取标题并将其空格字符替换为大写字符。然后,就像reduce-ing成一个对象一样简单:

const input=[{amount:23,bill:47,otherData:null,title:'cool title'},{amount:223,bill:427,otherData:null,title:'cooler title'},{amount:2313,bill:437,otherData:null,title:'super cool title'},{amount:123,bill:147,otherData:null,title:'coolest title'}]

console.log(
  input.reduce((a, item) => {
    const { title } = item;
    const camel = title.replace(/ ./g, chars => chars[1].toUpperCase());
    a[camel] = item;
    return a;
  }, {})
);

关于javascript - 从具有自定义键值的对象数组创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51166068/

相关文章:

arrays - 根据参数从函数内部的数组返回值

java - 用新行加入一个 json 字符串值

matlab如何遍历工作区中的所有对象

javascript - 复合对象上的 Object.Assign

javascript - 动态更改元素的子属性数组

Javascript 无法识别 "this"对象

javascript - 为什么我的时间/日期选择器格式会增加分钟数?

java - 查找数组中最小的数字错误

java - 如何将对象序列化为 CSV 文件?

javascript - 用于播放连续 mp3 文件的 HTML 按钮