如何将JSON转换为JS中的属性数组,无论JSON的深度是什么?
JSON
{
"foo": {
"bar": {
"baz": "UP"
}
}
}
键/值属性
{
"foo.bar.baz": "UP"
}
我当前的代码只处理一个级别,而不是n:
var user = {name: 'Corbin', age: 20, location: 'USA'},
key;
for (key in user) {
if (user.hasOwnProperty(key)) {
console.log(key + " = " + user[key]);
}
}
谢谢:D
答案 0 :(得分:3)
基本上,如果一个成员是一个对象,则进行递归调用,否则,更新输出对象:
data = {
foo: "hello",
bar: {
baz: {
qux: "UP"
},
spam: 'ham'
}
}
function unwrap(obj, prefix) {
var res = {};
for (var k of Object.keys(obj)) {
var val = obj[k],
key = prefix ? prefix + '.' + k : k;
if (typeof val === 'object')
Object.assign(res, unwrap(val, key)); // <-- recursion
else
res[key] = val;
}
return res;
}
console.log(unwrap(data))
&#13;