我有类似这样的数据。
[
{
key: 'myKey'
value: 'myValue'
},
{
key: 'mySecondKey'
value: 'mySecondValue'
},
{
key: 'myThirdKey'
value: 'myThirdValue'
},
]
对象的数量取决于帐户设置的值而有所不同。我正在尝试以看起来像这样的格式返回它
{
mykey: 'myValue'
mySecondKey: 'mySecondValue'
myThirdkey: 'myThirdValue'
}
关于我将如何执行此操作的任何建议?
答案 0 :(得分:2)
您可以做一些事情,例如
const src = [{key:'myKey',value:'myValue'},{key:'mySecondKey',value:'mySecondValue'},{key:'myThirdKey',value:'myThirdValue'},],
result = Object.assign({}, ...src.map(o => ({[o.key]: o.value})))
console.log(result)
.as-console-wrapper{min-height:100%;}
答案 1 :(得分:1)
您可以为此使用reduce
:
const data = [{key:"myKey",value:"myValue"},{key:"mySecondKey",value:"mySecondValue"},{key:"myThirdKey",value:"myThirdValue"}];
const res = data.reduce((obj, {key, value}) => ({...obj, [key]: value}), {});
console.log(res);
答案 2 :(得分:0)
其他答案可行,但我觉得它们有点复杂,这是一个简单的for循环:
const data = [
{
key: 'myKey',
value: 'myValue'
},
{
key: 'mySecondKey',
value: 'mySecondValue'
},
{
key: 'myThirdKey',
value: 'myThirdValue'
}
];
const result = {};
for(const {key, value} of data) {
result[key] = value;
}
console.log(result);