2015-11-08 65 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>');