Сообщение от tsigel
|
var obj = {
"database.host": "127.0.0.1",
"database.user": "test",
"database.password": "qwerty",
"rest.photo.host": "127.0.0.2",
"rest.users.host": "127.0.0.3",
"rest.users.password": "p@ssw0rd",
"baseUrl": "test.com",
"limit": 10
};
var result = {};
Object.keys(obj).forEach(function (name) {
var path = result, names = name.split("."), len = names.length;
names.forEach(function (subName, index) {
if (!path[subName]) {
if (index == len - 1) {
path[subName] = obj[name];
} else {
path[subName] = {};
}
}
path = path[subName];
});
});
alert(JSON.stringify(result , "", 4));
|
Я вот сделал чуток по-другому, но работает только если оставить "database.host": "127.0.0.1". Где ошибка?
var obj = {
"database.host": "127.0.0.1",
"database.user": "test",
"database.password": "qwerty",
"rest.photo.host": "127.0.0.2",
"rest.users.host": "127.0.0.3",
"rest.users.password": "p@ssw0rd",
"baseUrl": "test.com",
"limit": 10
};
var len;
var names;
var res;
var result = {};
var keys = Object.keys(obj);
function createObject (name)
{
res =result;
names=name.split('.');
len=names.length;
names.forEach (resultObject);
};
for (var i=0;i<keys.length;i++)
{
var arr =[];
arr[0]=keys[i];
arr.forEach(createObject);
}
function resultObject (subName, index)
{console.log(index+'-'+subName);
if (!res[subName])
{
if (index == len-1)
{
res[subName] = obj[keys];
}
else
{
res[subName] = {};
}
}
res = res[subName];
};
alert (JSON.stringify(result , "", 4));
[/quote]