将特定值的javascript数组映射为新键

时间:2018-06-09 12:51:44

标签: javascript lodash

所以我有这种数组

columnData:[
 {
   title: 'Male Members',
   key: 'm_members'
 }
 {
   title: 'Female Members',
   key: 'f_members'
 }
]

我希望把它变成这样的东西

newColumn: {
  m_members: 'Male Members',
  f_members: 'Female Members
}

如何用javascript或lodash做到这一点?

4 个答案:

答案 0 :(得分:1)

使用Array.reduceObject.assign

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获得的valuecolumnData填充新对象:

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循环就可以了。