我有一个这样的对象:
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1}
我想把它改成像这样的对象:
{
"prop": {
"health": 1,
"cost":1,
"time":1
}
}
这是我的代码:
_.each(data, function (value, key) {
var split = key.split('.')
if (split.length > 1) {
data[split[0]] = data[split[0]] || {}
data[split[0]][split[1]] = value
delete data[key]
}
})
但这仅适用于1级嵌套。您如何编写它以确保它适用于您需要的深层嵌套属性?
答案 0 :(得分:7)
您可以使用_.transform
和_.set
的组合,例如
data = _.transform(data, function(transformed, val, key) {
_.set(transformed, key, val);
});
结果
{"prop":{"health":1,"cost":1,"time":1}}
答案 1 :(得分:1)
如果没有库,就会出现这样的情况:
(function(){
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1, "prop.test.fun" : 1, "prop.test.sun" : 1};
var obj = {}; //will hold the object all parsed out
Object.keys(data).forEach( function (key) { //loop through the keys in the object
var val = data[key]; //grab the value of this key
var step = obj; //reference the object that holds the values
key.split(".").forEach(function(part, index, arr){ //split the parts and loop
if(index===arr.length-1){ //If we are at the last index, than we set the value
step[part] = val;
} else if(step[part]===undefined) { //If we have not seen this key before, create an object
step[part] = {};
}
step = step[part]; //Step up the object we are referencing
});
} );
console.log(obj);
}());
或双减少循环
(function(){
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1, "prop.test.fun" : 1, "prop.test.sun" : 1};
var result = Object.keys(data).reduce( function (obj, key) { //loop through the keys in the object
var val = data[key]; //grab the value of this key
key.split(".").reduce(function(step, part, index, arr){ //split the parts and loop
if(index===arr.length-1){ //If we are at the last index, than we set the value
step[part] = val;
} else if(step[part]===undefined) { //If we have not seen this key before, create an object
step[part] = {};
}
return step[part]; //Step up the object we are referencing
}, obj);
return obj;
}, {});
console.log(result);
}());
答案 2 :(得分:0)
根据许多因素(例如,如果原始对象始终包含您要删除的键等),您可以使用_.set
:
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1};
_.each(data, function (value, key) {
delete data[key];
_.set(data, key, value);
});
如果路径不存在, _.set
将创建路径。以上结果如下:
{"prop":{"health":1,"cost":1,"time":1}}
{"prop.health": 1, "prop.cost.food":1, "prop.time":1}
会导致:
{"prop":{"health":1,"cost":{"food":1},"time":1}}