2016-09-28 103 views
-2

我使用nodejs創建項目。我想的對象數組轉換成簡單array.For例如將對象數組轉換爲簡單數組nodejs

var test = [ { id: '1111', 
     type: 'sdfsdf' 
     }, 
     { id: 'df45', 
     type: 'fsdsdf', 
    }] 

我需要

var actual = [111,'sdfsdf'], ['df45','fsdsdf']. 
+1

只需使用'陣列#map' ... – Rayon

+0

你能不能給我一個例子嗎? – Karan

+3

'test.map((el)=>([el.id,el.type]))' – Rayon

回答

2

我會提出了基於動態的數字鍵的此解決方案:

var arr = test.map(function(obj){ 
    return Object.keys(obj). // convert object to array of keys 
     reduce(function(arr, current){arr.push(obj[current]); return arr}, []); // generate a new array based on object values 
}); 
+0

謝謝....這對我有用 – Karan

0

這可以通過使用Array.map()如下進行:

var actual = [] 

test.map(function(object) { 
    actual.push(objectToArray(object)) 
}) 

function objectToArray(obj) { 
    var array = [] 

    // As georg suggested, this gets a list of the keys 
    // of the object and sorts them, and adds them to an array 
    var obj_keys = Object.keys(obj).sort() 


    // here we iterate over the list of keys 
    // and add the corresponding properties from the object 
    // to the 'array' that will be returned   
    for(var i = 0; i < obj_keys.length; i++) { 
     array.push(obj[obj_keys[i]]) 
    } 
    return array 
} 

的函數objectToArray接受任何對象並將其轉換爲數組,以便它可以靈活,而不管對象內的鍵。

+0

我會使用Object.keys(...)。sort ()'或者類似的東西以防萬一。 – georg

+0

@georg Object.keys()更清潔,是的,你是對的:)但爲什麼sort()部分?我不明白 –

+1

想象一下'{id:xxx,type:foo},{type:bar,id:zzz}'。因此,無論是「排序」還是更好,保存第一個對象的'.keys'並迭代它。 – georg