2017-02-07 24 views
1

我有對象的數組:如何在loDash中使用reduce方法?或JavaScript對象取一個陣列中,並使一個對象

` 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;我不知道我應該如何遍歷數組?看着Doc的他們的例子顯示添加或推入陣列..我只想要一個對象..我知道它可以完成。如果他們是一個更好的方式,我也打開以及

在此先感謝。

+0

參見http://stackoverflow.com/questions/42068529/flatten-an-array-of-objects-containing-key-值/ 42068621#42068621 –

回答

0

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);

+0

這完成工作完成謝謝! – Dumas000

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"} 
相關問題