我在SO上使用方法来展平数组javascript,即将[1,[2,3]]
转换为[1,2,3]
。但我正在寻找一种简洁的方法来平整字典,同时保留键。具体来说,我想要一个看起来像这样的字典:
{'key1':1,'key2':{'key3':2,'key4':3,'key5':{'key6':4}}}
转换为:
{'key1':1, 'key2.key3':2,'key2.key4':3,'key2.key5.key6':4}
确切的输出格式(字典,对列表等)并不重要,只要它明确地将嵌套键的字符串与值相关联即可。出于我的目的,也可以假设没有任何键包含.
字符,因此它可以用来表示下一个键。
答案 0 :(得分:4)
var keys = {'key1':1,'key2':{'key3':2,'key4':3,'key5':{'key6':4}}}, result = {};
function serialize(keys, parentKey){
for(var key in keys){
if(parseInt(keys[key], 10)){
result[parentKey+key] = keys[key];
}else{
serialize(keys[key], parentKey+key+".");
}
}
}
serialize(keys, "");
console.log(result);
希望这就是你想要的。
答案 1 :(得分:0)
这是另一种解决问题的方法。
var myDict = {'key1':1,'key2':{'key3':2,'key4':3,'key5':{'key6':4}}};
function flattenDict(dictToFlatten) {
function flatten(dict, parent) {
var keys = [];
var values = [];
for(var key in dict) {
if(typeof dict[key] === 'object') {
var result = flatten(dict[key], parent ? parent + '_' + key : key);
keys = keys.concat(result.keys);
values = values.concat(result.values);
}
else {
keys.push(parent ? parent + '_' + key : key);
values.push(dict[key]);
}
}
return {
keys : keys,
values : values
}
}
var result = flatten(dictToFlatten);
var flatDict = {};
for(var i = 0, end = result.keys.length; i < end; i++) {
flatDict[result.keys[i]] = result.values[i];
}
return flatDict;
}
flattenDict(myDict);
答案 2 :(得分:0)
此代码不使用全局变量来存储结果。
var dict = {'key1':1,'key2':{'key3':2,'key4':3,'key5':{'key6':4}}};
function flatten(obj, suffix, ans) {
for (var x in obj) {
var key;
if (suffix != '')
key = suffix + '.' + x;
else
key = x;
if (typeof obj[x] === 'object') {
flatten(obj[x], key, ans);
} else {
ans[key] = obj[x];
}
}
}
var x = {};
flatten(dict, "", x)
console.log(x)