我有一个JSON对象,在第一级有3个嵌套对象。
data{"key1":"value1", "key2":"value2",
"section1":"{"key1_1":"value1_1", "key1_2":"value1_2"}",
"section2":"{"key2_1":"value2_1", "key2_2":"value2_2", "key2_3":"value2_3"}",
"section3":"{"key3_1":"value3_1"}"
}
现在,使用NODE.JS,我需要将所有键值从嵌套移动到父对象,所有键值都在根级别,如下所示:
data{
"key1":"value1", "key2":"value2","key1_1":"value1_1", "key1_2":"value1_2", "key2_1":"value2_1", "key2_2":"value2_2", "key2_3":"value2_3", "key3_1":"value3_1"
}
答案 0 :(得分:3)
使用适当的对象,您可以迭代键,如果找到了对象,则使用找到的对象的内容再次调用该函数。
function flat(source, target) {
Object.keys(source).forEach(function (k) {
if (source[k]!== null && typeof source[k] === 'object') {
flat(source[k], target);
return;
}
target[k] = source[k];
});
}
var data = { "key1": "value1", "key2": "value2", "section1": { "key1_1": "value1_1", "key1_2": "value1_2" }, "section2": { "key2_1": "value2_1", "key2_2": "value2_2", "key2_3": "value2_3" }, "section3": { "key3_1": "value3_1" } },
flatObject = {};
flat(data, flatObject);
console.log(flatObject);
版本,其中JSON字符串作为值,try ... catch
语句用于测试值是否为JSON。
function flat(source, target) {
Object.keys(source).forEach(function (k) {
var o;
try {
o = JSON.parse(source[k]);
if (o && typeof o === 'object') {
flat(o, target);
} else {
target[k] = o;
}
} catch (e) {
target[k] = source[k];
}
});
}
var data = { "key1": "value1", "key2": "value2", "section1": "{\"key1_1\":\"value1_1\", \"key1_2\":\"value1_2\"}", "section2": "{\"key2_1\":\"value2_1\", \"key2_2\":\"value2_2\", \"key2_3\":\"value2_3\"}", "section3": "{\"key3_1\":\"value3_1\"}" },
flatObject = {};
flat(data, flatObject);
console.log(flatObject);
答案 1 :(得分:1)
您可以递归遍历数据并将其添加到空地图中:
var data = {
"key1":"value1", "key2":"value2",
"section1":{"key1_1":"value1_1", "key1_2":"value1_2"},
"section2":{"key2_1":"value2_1", "key2_2":"value2_2", "key2_3":"value2_3"},
"section3":{"key3_1":"value3_1"}
}
var fill = function(carry, obj) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
if (obj[key] instanceof Object) {
fill(carry, obj[key]);
}
else {
carry[key] = obj[key];
}
}
return carry;
}
var output = {}
fill(output, data);
console.log(output);