现在我知道有一些类似的问题,例如 this question和this 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/