【问题标题】:How do I use the reduce method in loDash? Or Javascript Take a Array of Objects and Make one Object如何在 loDash 中使用 reduce 方法?或者 Javascript 获取一组对象并创建一个对象
【发布时间】:2017-02-07 16:55:09
【问题描述】:

我有一个对象数组:

` 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's他们的例子显示添加或推送到数组..我只想要一个对象..我知道它可以完成。如果他们是更好的方式,我也愿意接受

提前致谢。

【问题讨论】:

标签: javascript arrays object lodash


【解决方案1】:

更短的等效解决方案:

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"}

【讨论】:

    【解决方案2】:

     tempArray = [
          { name: 'Lion-O' },
          { gender: 'Male' },
          { weapon: 'Sword of Omens' },
          { status: 'Lord of the Thundercats' },
        ]
       
       var newObject = {};
       
       for (var index in tempArray) {
         thisObject = tempArray[index];
         for (var key in thisObject) { 
           newObject[key] = thisObject[key];
         }                      
       }
       
       console.log(newObject);

    【讨论】:

      猜你喜欢
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多