Javascript-遍历Json对象并获取每个项目的层次结构键,包括嵌套的对象和数组
问题描述:
我想获取包括任何JSON对象在内的值和键,作为甚至可以用于复杂对象的通用方法
json
{
"timezone": 5.5,
"schedule": {
"type": "daily",
"options": {
"hour": 10,
"minute": 29
}
}
想要像这样的分层模式中的值和键
want the values and keys in hierarchical schema just like these
timezone - 5.5
schedule.type - daily
schedule.type.options.hour - 10
schedule.type.options.minute - 29
此外,我使用此函数可以获取JSON对象的所有对象键和值,即使在嵌套数组和对象中也是如此
Also, I used this function can get the JSON objects all objects keys and values even in the nested arrays and objects in that
function iterate(obj) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property]);
} else {
console.log(property , obj[property])
}
}
}
return obj;
}
PS-我也是还要将此用于数组
PS - Also I want to use this for arrays also
"dirs": [ { "watchDir": "Desktop/logs", "compressAfterDays": 50 }, { "watchDir": "Desktop/alerts", "timeMatchRegex": "(.*)(\\d{4})-(\\d{2})-(\\d{2})-(\\d{2})_(\\d{2})(.*)", }]
我想要的输出就是这样
dirs[0].watchdir="Desktop/alerts"
dirs[1].watchDir="Desktop/logs"
答
const obj = { "timezone": 5.5, "dirs": [ { "watchDir": "Desktop/logs", "compressAfterDays": 50 }, { "watchDir": "Desktop/alerts", "timeMatchRegex": "(.*)(\\d{4})-(\\d{2})-(\\d{2})-(\\d{2})_(\\d{2})(.*)", }] ,"schedule": { "type": "daily", "options": { "hour": 10, "minute": 29 }, 'available': true } };
function iterate(obj, str) {
let prev = '';
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
const s = isArray(obj) ? prev + str + '[' + property + ']' + '.' : prev + property + (isArray(obj[property]) ? '' : '.');
iterate(obj[property], s);
} else {
prev = (str != undefined ? str : '');
console.log(prev + property, '- ' + obj[property]);
}
}
}
return obj;
}
function isArray(o) {
return o instanceof Array;
}
iterate(obj);