我需要像这样转换“平面对象”(输入数据):
{
'prop1': 'value.1',
'prop2-subprop1': 'value.2.1',
'prop2-subprop2': 'value.2.2',
}
像这样的沉浸物体(输出数据):
{
'prop1': 'value.1',
'prop2': {
'subprop1': 'value.2.1',
'subprop2': 'value.2.2'
}
}
当然,解决方案必须为无限制的深层次做准备。
我的解决方案不起作用:
var inputData = {
'prop1': 'value.1',
'prop2-subprop1': 'value.2.1',
'prop2-subprop2': 'value.2.2',
};
function getImmersionObj(input, value) {
var output = {};
if ($.type(input) === 'object') { // first start
$.each(input, function (prop, val) {
output = getImmersionObj(prop.split('-'), val);
});
} else if ($.type(input) === 'array') { // recursion start
$.each(input, function (idx, prop) {
output[prop] = output[prop] || {};
output = output[prop];
});
}
return output;
}
console.log(getImmersionObj(inputData)); // return empty object
你能帮助我在我的代码中找到问题,或者你知道另一个更好的转换算法吗?
答案 0 :(得分:3)
您可以使用一个函数来分割值的路径并为其生成新对象。
function setValue(object, path, value) {
var way = path.split('-'),
last = way.pop();
way.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var object = { 'prop1': 'value.1', 'prop2-subprop1': 'value.2.1', 'prop2-subprop2': 'value.2.2' };
Object.keys(object).forEach(function (key) {
if (key.indexOf('-') !== -1) {
setValue(object, key, object[key]);
delete object[key];
}
});
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
var input = {
"property1": "value1",
"property2.property3": "value2",
"property2.property7": "value4",
"property4.property5.property6.property8": "value3"
}
function addProp(obj, path, pathValue) {
var pathArray = path.split('.');
pathArray.reduce(function (acc, value, index) {
if (index === pathArray.length - 1) {
acc[value] = pathValue;
return acc;
} else if (acc[value]) {
if (typeof acc[value] === "object" && index !== pathArray.length - 1) {
return acc[value];
} else {
var child = {};
acc[value] = child;
return child;
}
} else {
var child = {};
acc[value] = child;
return child;
}
}, obj);
}
var keys = Object.keys(input);
var output = {};
keys.forEach(function (k) {
addProp(output, k, input[k]);
});
console.log(output);