我有如下的对象结构
var obj = {
a : 1,
b : [x,y,z],
c : [0,1,3],
d : ['%','-','+']
}
Run Code Online (Sandbox Code Playgroud)
我想将该对象转换为以下格式
{
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 : ['%','-','+']
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果['%','-','+']在上述情况之后还有一个属性,则相同的过程继续..
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]] || {};
}
}
Run Code Online (Sandbox Code Playgroud)
请建议我完成这个逻辑.
这是一种可行的算法,但它只会为 ie 创建一个对象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": ['%','-','+']
}
];
Run Code Online (Sandbox Code Playgroud)
但无论如何,这是使用原始对象表示法的算法:
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;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果您需要单独的、独立的对象,您可以更改该行
newObj[obj[key]] = tempObj;
Run Code Online (Sandbox Code Playgroud)
类似的东西
newObj[obj[key]] = copyObject(tempObj);
Run Code Online (Sandbox Code Playgroud)
其中copyObject是创建对象深层副本的函数。但我想在这种情况下,性能会急剧下降,因为您一遍又一遍地复制相同的对象。
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |