从 JSON 中获取平面结构中的每个名称值
Get every name-value from JSON in flat structure
我有一个 JSON 文件,其中的数据结构如下:
{
"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;
}
可以通过递归函数来完成:
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/
我有一个 JSON 文件,其中的数据结构如下:
{
"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;
}
可以通过递归函数来完成:
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/