[英]How to merge 2 javascript objects into an array?
I have objects like this: 我有这样的对象:
{ "aa": "11", "bb" : "22", "cc" : "33" }
{ "aa": "text1", "bb" : "text2", "cc" : "text3" }
I need to merge these to become this array 我需要将它们合并成这个数组
[ ["text1", "11"], ["text2", "22"], ["text3", "33"] ]
Is there an easy way to do this? 是否有捷径可寻?
Here is some JS FP just for fun: 这是一些有趣的JS FP:
var o1 = { "aa": "11", "bb" : "22", "cc" : "33" },
o2 = { "aa": "text1", "bb" : "text2", "cc" : "text3" };
var values = function(obj) {
return Object.keys(obj).map(function(key) {
return obj[key];
});
};
function zip(arrays) {
return arrays[0].map(function(_,i){
return arrays.map(function(array) {
return array[i];
});
});
}
var zipped = zip([
values(o1),
values(o2)
]);
console.log(zipped);
http://jsfiddle.net/q3P2h/ http://jsfiddle.net/q3P2h/
PS: zip
function implementation borrowed at https://stackoverflow.com/a/10284006/251311 PS:通过https://stackoverflow.com/a/10284006/251311借用的
zip
函数实现
var objects = [{
"aa": "11",
"bb": "22",
"cc": "33"
}, {
"aa": "text1",
"bb": "text2",
"cc": "text3"
}];
var result = [];
for (var key in objects[1]) {
result.push([objects[1][key], objects[0][key]]);
}
console.log(result);
# [ [ 'text1', '11' ], [ 'text2', '22' ], [ 'text3', '33' ] ]
Or 要么
console.log(Object.keys(objects[1]).map(function(key) {
return [objects[1][key], objects[0][key]];
}));
# [ [ 'text1', '11' ], [ 'text2', '22' ], [ 'text3', '33' ] ]
If you had the objects in two different variables, like this 如果您的对象具有两个不同的变量,就像这样
var o1 = { "aa": "11", "bb" : "22", "cc" : "33" },
o2 = { "aa": "text1", "bb" : "text2", "cc" : "text3" };
then 然后
console.log(Object.keys(o2).map(function(key) {
return [o2[key], o1[key]];
}));
# [ [ 'text1', '11' ], [ 'text2', '22' ], [ 'text3', '33' ] ]
An easier way could be : 一个更简单的方法可能是:
var a = { "aa": "11", "bb": "22", "cc": "33" };
var b = { "aa": "text1", "bb": "text2", "cc": "text3" };
var c=[];
$.each(a, function (index, value) {
c.push(a[index], b[index]);
});
PS: Using jQuery . PS: 使用jQuery 。
Folks Try this one. 民间尝试一下。 Hope so it will work for you.
希望如此对您有用。
var x = { "aa": "11", "bb" : "22", "cc" : "33" }
var y = { "aa": "text1", "bb" : "text2", "cc" : "text3" }
var a = [];
var b = [];
for(var k in x){ a.push(k);}
for(var i = 0; i<a.length;i++){
var c = [];
c.push(x[a[i]]);
c.push(y[a[i]]);
b.push(c);
c = [];
}
console.log(b);
Thanks and regards. 谢谢并恭祝安康。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.