我有如下的对象结构
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]] || {};
}
}
请建议我完成这个逻辑。
答案 0 :(得分:3)
这是一个有效的算法,但它只会为x
,y
和z
创建一个对象,并引用同一个对象。
此外,以下示例假定键的顺序(由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;
}
<强> FIDDLE 强>
顺便说一句,如果您需要单独的独立对象,您可以更改行
newObj[obj[key]] = tempObj;
类似
newObj[obj[key]] = copyObject(tempObj);
其中copyObject
是一个创建对象深层副本的函数。但我想在这种情况下,由于你一遍又一遍地复制相同的对象,性能会急剧下降。