将一种类型的javascript对象转换为另一种类型

时间:2012-11-26 20:49:59

标签: javascript object

我需要转换一种类型的JavaScript对象:

object1: [{"a":"value1", "b":"value2", "c":"value3"}, {"d":"value4","e":"value5","f":"value6"}] 

到另一种类型的对象:

object2 : {"value1":["value1", "value2", "value3"], "value4":["value4","value5","value6"]}

我尝试使用此功能转换它:

function toObject(arr) {
   var rv = {};
   for (var i = 0; i < arr.length; ++i) {
      rv[i] = arr[i];
   }
   return rv;
}

但是我得到数字索引([0],[1])而不是“value1”和“value4”。能否请你给我一些提示如何从object1转换为object2。谢谢。

1 个答案:

答案 0 :(得分:2)

你想要的是连接矢量囚犯吗?

尝试:

function toObject(arr) {
   var rv = {}, k;
   for (var i = 0; i < arr.length; ++i) {
     for(k in arr[i]){
       rv[k] = arr[i][k];
     }
   }
   return rv;
}

如果这不是你想要的,那试试这个: [已修复(在用户 @ user1689607 的帮助下)]

<强> [编辑]

Object.keys在旧版浏览器中不起作用。的 [固定]

function toObject(arr,_sort) {
    //param1 = Object, param2 = (true:sort, false:default)
    var rv = {}, k, firstV = null, keys, obj, tmp, j,
       ObjK = Object.keys ? function(ke){
            return Object.keys(ke);
       } : function(ke){
            var r = [];
            for(var o in ke){
                r[r.length] = o;
            }
            return r;
       };

    for (var i = 0; i < arr.length; ++i) {
        obj = arr[i];
        tmp = [];
        keys = _sort===true ? ObjK(obj).sort() : ObjK(obj);
        tmp = [obj[keys[0]]];
        for (j = 0; j < keys.length; ++j) {
            tmp[tmp.length] = obj[keys[j]];
        }
        rv[obj[keys[0]]] = tmp;
        firstV = null;
    }
    return rv;
}

//sort
console.log(
    toObject([{"a":"value1", "b":"value2", "c":"value3"}, {"d":"value4","e":"value5","f":"value6"}]),
true);

//default
console.log(
    toObject([{"a":"value1", "b":"value2", "c":"value3"}, {"d":"value4","e":"value5","f":"value6"}])
);