我有一个JSON文件,其数据结构如下:
{
"first": {
"second": "example",
"third": {
"fourth": "example2",
"fifth": "example3"
}
}
}
有没有办法将它转换为扁平结构,只能获得带字符串值的名称 - 值对?从这个JSON我想得到这样的东西:
{
"second": "example",
"fourth": "example2",
"fifth": "example3"
}
答案 0 :(得分:2)
这可能会让您在纯JavaScript中了解如何展平对象。这很粗糙,但可以扩展:
function flatten(obj) {
var flattened = {};
for (var prop in obj)
if (obj.hasOwnProperty(prop)) {
//If it's an object, and not an array, then enter recursively (reduction case).
if (typeof obj[prop] === 'object' &&
Object.prototype.toString.call(obj[prop]) !== '[object Array]') {
var child = flatten(obj[prop]);
for (var p in child)
if (child.hasOwnProperty(p))
flattened[p] = child[p];
}
//Otherwise if it's a string, add to our flattened object (base case).
else if (typeof obj[prop] === 'string')
flattened[prop] = obj[prop];
}
return flattened;
}
答案 1 :(得分:2)
可以通过递归函数完成:
var obj = {
"first": {
"second": "example",
"third": {
"fourth": "example2",
"fifth": "example3"
}
}
};
function parseObj(_object) {
var tmp = {};
$.each(_object, function(k, v) {
if(typeof v == 'object') {
tmp = $.extend({}, tmp, parseObj(v));
} else {
tmp[k] = v;
}
});
return tmp;
}
var objParsed = {};
objParsed = parseObj(obj);
console.log(objParsed);
这是JSFiddle的工作:https://jsfiddle.net/0ohbyu7b/