2015-11-08 38 views

回答

0

這裏有一個解決方案使用下劃線:

var keys = _.keys(data); 

// create an array of all the values for each object 
var valuesList = _.zip.apply(null, _.values(data)); 

// map across each value list to create the object 
var result = _.map(valuesList, function(values){ 
    return _.object(keys, values) 
}); 
+0

簡單就是美。我喜歡沒有'爲'哈哈的循環 –

1

您可以這樣做,假設當前索引對應於每個屬性中的正確值。

var obj = { 
    name: [ 'foo', 'bar' ], 
    email: [ '[email protected]', '[email protected]' ], 
    comment: [ 'message', 'bmessage' ] 
}; 

var arr = []; 

for (var i = 0; i < obj.name.length; i++) { 
    arr.push({ 
    name: obj.name[i], 
    email: obj.email[i], 
    comment: obj.comment[i] 
    }); 
} 

console.log(arr); 

輸出:

[ { name: 'foo', email: '[email protected]', comment: 'message' }, 
    { name: 'bar', email: '[email protected]', comment: 'bmessage' } ] 

這可有點容易出錯不過,如果指數不匹配正確的值,或者如果你沒有在每個屬性值是相同的。

0

你可以運行該代碼.....

var array = []; // declare a new array 

for(var i = 0 ;i <a.name.length;i++){ 
    var obj = {}; // declare new objcet 
    obj.name = a.name[i]; 
    obj.email = a.email[i]; 
    obj.comment = a.comment[i]; 

    array.push(obj); // push object into array 

} 

console.log(array); 
1

我建議遍歷所有的鍵,然後在屬性的內容。

var obj = { 
 
     name: ['foo', 'bar'], 
 
     email: ['[email protected]', '[email protected]'], 
 
     comment: ['message', 'bmessage'] 
 
    }, 
 
    array = []; 
 
Object.keys(obj).forEach(function (k) { 
 
    obj[k].forEach(function (a, i) { 
 
     array[i] = array[i] || {}; 
 
     array[i][k] = a; 
 
    }); 
 
}); 
 
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');