2017-04-11 102 views
-1

我有一個來自服務器響應的對象數組。遍歷對象鍵和操作鍵值

陣列結構:

[ 
    { 
    col1: ["a", "b"], 
    col2: ["c", "d"] 
    }, 

    { 
    col1: ["e", "f"], 
    col2: ["g", "h"] 
    } 
] 

我想期望的輸出陣列是在這種形式:

[ 
    { 
    col1: "b", 
    col2: "d" 
    }, 

    { 
    col1: "f", 
    col2: "h" 
    } 
] 

基本上我想對象密鑰值,它是一個數組最初到單個轉換值,該值將成爲Object鍵數組的第二個元素。

我能夠做轉換通過使用toString()轉換對象鍵陣列爲逗號分隔字符串,然後做​​但我無法遍歷對象鍵。

寧願使用地圖中ES6輸入迭代

+1

這可以通過使用簡單的循環來實現,你嘗試過什麼? – Satpal

+1

可能的重複[如何循環或枚舉JavaScript對象?](http://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – Arg0n

+0

我正在使用es6,使用map進行循環。我嘗試了雙映射,但沒有按照優化的方式迭代。 –

回答

0

你可以使用的Array#mapObject.assignspread syntax ...組合與想要的鍵/值的新對象的內部映射。

var data = [{ col1: ["a", "b"], col2: ["c", "d"] }, { col1: ["e", "f"], col2: ["g", "h"] }], 
 
    result = data.map(o => Object.assign({}, ...Object.keys(o).map(k => ({ [k]: o[k][1] })))); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

0

下面的代碼應工作按您的規範。

var arr = [ {col1: ["a","b"], col2: ["c","d"] }, {col1: ["e","f"], col2: ["g","h"] } ] 
 

 

 
// [ {col1: "b" , col2: "d" }, {col1: "f", col2: "h" } ] 
 

 
arr2 = []; 
 

 
arr.forEach(e => { 
 
    let currObj = {}; 
 
    Object.keys(e).forEach(f => { 
 
    currObj[f] = e[f][1] 
 
    }) 
 
    arr2.push(currObj) 
 
}) 
 

 
console.log(arr2);

+0

鍵名是可變的,不是固定的,因爲它來自服務器響應。 –

+1

更新我的代碼,現在應該工作。 –

+0

工程很好。保持 ! –

0

可能的解決方法使用Array#reduceObject.keys

var arr = [ {col1: ["a","b"], col2: ["c","d"] }, {col1: ["e","f"], col2: ["g","h"] } ], 
 
    res = arr.reduce(function(s,a) { 
 
     var obj = {}; 
 
     Object.keys(a).map(function(c) { 
 
     obj[c] = a[c][1]; 
 
     }) 
 
     s.push(obj); 
 
     return s; 
 
    }, []); 
 
    
 
    console.log(res);

+0

謝謝。這是我正在尋找的。奇蹟般有效。 –

0

var data = [ {col1: ["a","b"], col2: ["c","d"] }, {col1: ["e","f"], col2: ["g","h"] } ]; 
 
var res=[]; 
 
var d = data.reduce(function(all,item){ 
 
    res.push({col1:item.col1[1],col2:item.col2[1]}); 
 
    return all; 
 
},{}); 
 

 
console.log(res);