我有一个像这样的对象
{
"CPU": {
"Architecture": {
"X86": 0,
"Other": 0,
"X86_64": 6
}
},
"Platform": {
"Os": {
"Mac": 0,
"Linux": 5,
"Other": 0,
"Windows": 0
}
}
}
如何将其转换为这样的地图?
"CPU.Architecture.X86": 0
"Platfrom.Os.Mac":0
"Platfrom.Os.Linux":5
是否已经有现成的解决方案?
答案 0 :(得分:2)
如果您的目标是连接嵌套对象属性键,则没有内置函数。但是,实现自己的解决方案非常简单:
// Concatenate nested object property keys with a dot:
function dotnotation(obj, dst = {}, prefix = '') {
Object.entries(obj).forEach(([key, val]) => {
if (val && typeof val == 'object') dotnotation(val, dst, prefix + key + '.');
else dst[prefix + key] = val;
});
return dst;
}
// Example:
console.log(dotnotation({a:{b:1, c:2}, d:3})); // {'a.b':1, 'a.c':2, 'd':3}

Object.entries()
是即将推出的ES2017标准的一部分。
答案 1 :(得分:1)
你可以尝试这样的事情,假设你的对象只是从数据中创建的:
function flatten(obj, prev = "", res = {}){
for(f in obj){
if (obj.hasOwnProperty(f)){
if(obj[f].constructor === Object){
prev = prev + f + ".";
flatten(obj[f], prev, res);
}else{
res[prev + f] = obj[f];
}
}
}
return res;
}
let a = {
"CPU": {
"Architecture": {
"X86": 0,
"Other": 0,
"X86_64": 6
}
},
"Platform": {
"Os": {
"Mac": 0,
"Linux": 5,
"Other": 0,
"Windows": 0
}
}
};
console.log(flatten(a))
它将使用for... in循环。
// more consisely
function flatten(obj, prev = "", res = {}){
for(f in obj){
if (obj.hasOwnProperty(f)){
if (obj[f].constructor === Object){
if(typeof obj[f] !== "object") res[prev + f] = obj[f];
else flatten(obj[f], prev + f + ".", res);
}
}
}
return res;
}
答案 2 :(得分:0)
随意尝试该项目: