2017-05-22 64 views
0

我花了整晚的時間研究這個問題,我知道答案很接近;但我仍然有很多語法工作要做。請不要低估這一點 - 這樣做只會阻止像我這樣的新手提問。 我需要創建一個接受簡單對象作爲參數的函數,並返回一個數組數組。函數應該在具有任意數量的屬性列的對象上使用簡單的字符串/數字值。我將展示並解釋代碼我的工作,我會在下面附上:JavaScript遍歷對象將數組追加到數組

//my first code: 
 
var hi = {a: 1, b: 2, c: 3}; 
 
var props = new Array([],[],[]); 
 
var lent = 0; 
 
function newWave(hi){ 
 
    for(var key in hi){ 
 
    props[lent].push(key); 
 
    props[lent].push(hi[key]); 
 
    lent = lent + 1; 
 
    } 
 
    return props; 
 
} 
 
newWave(hi); 
 

 
//function yields: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ] 
 
//The return output is correct, but I need a universal code; 
 
//looking at the number of columns in variable 'props', you can 
 
//tell that this function only works on objects with 3 roperties.

//My second code: 
 
function newWave(hi) { 
 
    var props = []; 
 
    var outcome = []; 
 
    for (var i = 0; i<1; i++){ 
 
    for(var key in hi){ 
 
     props.push(key, hi[key]); 
 
     outcome.push(props); 
 
    } 
 
    return outcome; 
 
    } 
 
} 
 
newWave(hi); 
 
//This returns: 
 
//[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ], 
 
// [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ], 
 
// [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ] 
 
//I feel like the answer is so close, but it's been 7 hours working on this, 
 
//your help is greatly appreciated

回答

1
function newWave (hi) { 
    return Object.keys(hi).map(v => [v, hi[v]]); 
} 

所以在這裏我們使用Object.keys得到一個對象屬性的數組,然後對於每一個我們將它們映射到一個數組,其屬性爲冷杉t項目和其值作爲第二個

0

使用Object.keys獲取數組中的對象中存在的所有鍵。遍歷數組和推鍵和值到另一個陣列

var hi = { 
 
    a: 1, 
 
    b: 2, 
 
    c: 3, 
 
    d: 4 
 
}; 
 
var finalArray = [] 
 

 
function newWave(hi) { 
 
    var getKeys = Object.keys(hi); 
 
    for (var i = 0; i < getKeys.length; i++) { 
 
    var tempArray = []; 
 
    tempArray.push(getKeys[i].toString(), hi[getKeys[i]]) 
 
    finalArray.push(tempArray) 
 
    } 
 
    return finalArray; 
 
} 
 

 
console.log(newWave(hi));

1

您不必之前定義數組,你可以在你的函數來創建新的空數組,循環傳遞的對象並推動[key, value]

var hi = {a: 1, b: 2, c: 3}; 
 

 
function newWave(obj) { 
 
    var r = [] 
 
    for (var key in obj) r.push([key, obj[key]]) 
 
    return r; 
 
} 
 

 
console.log(JSON.stringify(newWave(hi)))

也有新的js方法,稱爲Object.entries(),可以返回此結果。

var hi = {a: 1, b: 2, c: 3}; 
 

 
function newWave(obj) { 
 
    return Object.entries(obj) 
 
} 
 

 
console.log(newWave(hi))

+0

Didn't瞭解項目的方法,很好 – juvian

+0

優秀的快捷方式,但對於這項任務, '迴歸' 是必需的,而不是CONSOLE.LOG。它必須在功能的傳統輪廓中。 – Joan