如何在loDash中使用reduce方法?或者Javascript获取一个对象数组并生成一个对象
我有一个对象数组:如何在loDash中使用reduce方法?或者Javascript获取一个对象数组并生成一个对象,javascript,arrays,object,lodash,Javascript,Arrays,Object,Lodash,我有一个对象数组: ` tempArray = [ { name: 'Lion-O' }, { gender: 'Male' }, { weapon: 'Sword of Omens' }, { status: 'Lord of the Thundercats' }, ] ` 要转换为的对象: `{ name: 'Lion-O', gender: 'Male,', weapon: 'Sword of Omens', sta
` tempArray = [
{ name: 'Lion-O' },
{ gender: 'Male' },
{ weapon: 'Sword of Omens' },
{ status: 'Lord of the Thundercats' },
]
`
要转换为的对象:
`{
name: 'Lion-O',
gender: 'Male,',
weapon: 'Sword of Omens',
status: 'Lord of the Thundercats'
}`
我尝试在LoDash中使用reduce
const tempObj = _.reduce(tempArray, (r, v, k) => {
return r
})
console.log(tempObj);
//=> { name: 'Lion-O' }
我不确定应该如何迭代数组?查看Doc的示例,他们的示例显示添加或推送到数组上。。我只想要一件东西。。我知道这是可以做到的。如果他们的方法更好,我也愿意接受
提前谢谢。
tempArray=[
{name:'Lion-O'},
{性别:'男性'},
{武器:'凶兆之剑'},
{状态:'雷霆猫之王'},
]
var newObject={};
for(临时数组中的var索引){
thisObject=tempArray[index];
对于(此对象中的var键){
newObject[key]=此对象[key];
}
}
console.log(newObject)代码>较短的等效解决方案:
const tempArray = [
{ name: 'Lion-O' },
{ gender: 'Male' },
{ weapon: 'Sword of Omens' },
{ status: 'Lord of the Thundercats' },
];
const newObj = Object.assign({}, ...tempArray);
console.log(newObj);
// Object {name: "Lion-O", gender: "Male", weapon: "Sword of Omens", status: "Lord of the Thundercats"}
看见