5

我有如下的对象结构

var obj = {
   a : 1,
   b : [x,y,z],
   c : [0,1,3],
   d : ['%','-','+']
}

我想将该对象转换为以下格式

{
  1 : {
     x : {
         0 : ['%','-','+'], // Last index remains as an array
         1 : ['%','-','+'],
         3 : ['%','-','+']
     },
     y : {
         0 : ['%','-','+'], // Last index remains as an array
         1 : ['%','-','+'],
         3 : ['%','-','+']
     },
     z : {
         0 : ['%','-','+'], // Last index remains as an array
         1 : ['%','-','+'],
         3 : ['%','-','+']
     }
  }
}

['%','-','+']如果在上述情况下还有一个属性,则继续相同的过程。

var v = {}/* Object of above */, keys = Object.keys(v), simplifiedColumns = {};
for (var i = 0, l = keys.length; i < l ; i++) {
        if (v[i] instanceof Array) {

        }else{
              simplifiedColumns[keys[i]] = simplifiedColumns[keys[i]] || {};
        }
}

请建议我完成这个逻辑。

4

1 回答 1

3

这是一种有效的算法,但它只会为 ie 创建一个对象xyz引用同一个对象。

此外,以下示例假定键的顺序(由 提供Object.keys())与定义对象的顺序相同。情况并非总是如此,因此更好的解决方案是将对象更改为数组:

var obj = [
   {
        "key": "a",
        "value": 1
   },
   {
        "key": "b",
        "value": ["x","y","z"]
   },
   {
        "key": "c",
        "value": [0,1,3]
   },
   {
        "key": "d",
        "value": ['%','-','+']
   }
];

但无论如何,这里是使用原始对象符号的算法:

var obj = {
   a : 1,
   b : ["x","y","z"],
   c : [0,1,3],
   d : ['%','-','+']
};

var keys = Object.keys(obj);

//set tempObj to the last array
var tempObj = obj[keys[keys.length - 1]];

//traverse the rest of the keys backwards
for (var i = keys.length - 2; i >= 0; i--) {
    var key = keys[i];

    //create new empty object
    var newObj = {};

    //append "tempObj" to that object and using the keys that are in the current array
    //or if the property isn't an array, use the property itself as key
    if (Array.isArray(obj[key])) {
        for (var k = 0; k < obj[key].length; k++) {
            newObj[obj[key][k]] = tempObj;
        }
    } else {
        newObj[obj[key]] = tempObj;
    }
    //override tempObj with the new created object
    tempObj = newObj;
}

小提琴

顺便说一句,如果您需要单独的独立对象,您可以更改行

newObj[obj[key]] = tempObj;

类似于

newObj[obj[key]] = copyObject(tempObj);

wherecopyObject是一个创建对象的深层副本的函数。但我想在这种情况下,性能会急剧下降,因为你一遍又一遍地复制相同的对象。

于 2013-06-18T06:43:56.333 回答