Javascript 以平面结构从JSON获取每个名称值
我有一个JSON文件,其中的数据结构如下:Javascript 以平面结构从JSON获取每个名称值,javascript,json,structure,Javascript,Json,Structure,我有一个JSON文件,其中的数据结构如下: { "first": { "second": "example", "third": { "fourth": "example2", "fifth": "example3" } } } 有没有一种方法可以将其转换为平面结构,以仅获取具有字符串值的名称-值对?从这个JSON中,我想得到如下内容: { "second": "example",
{
"first": {
"second": "example",
"third": {
"fourth": "example2",
"fifth": "example3"
}
}
}
有没有一种方法可以将其转换为平面结构,以仅获取具有字符串值的名称-值对?从这个JSON中,我想得到如下内容:
{
"second": "example",
"fourth": "example2",
"fifth": "example3"
}
这可能会让您在纯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;
}
这可能会让您在纯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;
}
可以通过递归函数完成:
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);
下面是正在工作的JSFIDLE:它可以通过递归函数完成:
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);
下面是工作的JSFIDLE:@deviant看看这个:@deviant看看这个: