多重数组转换对象?


arr = [ {1:"a"},{2:"b"}]
大概就是上边这种数组,怎么转换成下边这种对象。
obj = {1:"a",2:"b"}

向后台传参数的话,是不是下边这种更合适一些?

jquery javascript对象 JavaScript javascript数组 类型转换

amonn 8 years, 9 months ago

@代码宇宙 的答案能够完美实现。
但你的数据结构或许不是最好的选择,纯数字连续的属性值,应该直接做成数组,即 ['a', 'b'] 这种形式。

opera answered 8 years, 9 months ago


 var arr = [ {1:"a"},{2:"b"}];
var obj = {};

//es2015
arr.forEach(function(v){
  Object.assign(obj, v);
});

console.log(obj);


 var arr = [ {1:"a"},{2:"b"}];
var obj = {};

//jQuery version
jQuery.each(arr,function(k, v){
  jQuery.extend(obj, v);
});

console.log(obj);

撸出一个大明湖 answered 8 years, 9 months ago


 var arr = [{1:'a'},{2:'b'}];
var obj = eval('('+(JSON.stringify(arr[0])+JSON.stringify(arr[1])).replace(/}{/,',')+')');
console.log(obj);
//Object {1: "a", 2: "b"}

【絕對領域】 answered 8 years, 9 months ago


 var obj = {};
for (var i = 0; i < arr.length; i++) {
    for (var k in arr[i]) {
        obj[k] = arr[i][k];
    }
}

湫山·黄泉 answered 8 years, 9 months ago

Your Answer