所以我有这种数组
columnData:[
{
title: 'Male Members',
key: 'm_members'
}
{
title: 'Female Members',
key: 'f_members'
}
]
我希望把它变成这样的东西
newColumn: {
m_members: 'Male Members',
f_members: 'Female Members
}
如何用javascript或lodash做到这一点?
答案 0 :(得分:1)
var columnData = [{title: 'Male Members',key: 'm_members'},{title:'Female Members',key: 'f_members'}];
newColumn = columnData.reduce((a,{title, key}) => Object.assign(a, {[key]:title}),{});
console.log(newColumn);
答案 1 :(得分:1)
您可以使用Object.assign
并传播语法...
来执行此操作。
const data = [{title: 'Male Members',key: 'm_members'}, {title: 'Female Members',key: 'f_members'}]
const result = Object.assign({}, ...data.map(({title, key}) => ({[key]: title})));
console.log(result)
答案 2 :(得分:1)
您可以使用forEach
方法遍历项目,然后使用从key
获得的value
和columnData
填充新对象:
const columnData = [{title: 'Male Members',key: 'm_members'},{title: 'Female Members',key: 'f_members'}]
let newData = {};
columnData.forEach(e => {
newData[e.key] = e.title
})
console.log(newData)
答案 3 :(得分:0)
const result = {};
for(const {title, key} of columnData)
result[key] = title;
一个简单的for循环就可以了。