我有这段代码,但它没有打印子键......
const replacements = {
name: 'Bob',
age: 37
}
interpolate('My name is ${name}, and I am ${age}.', replacements)
何时打印对象:someKey [Object object]
我的结果(例子):
for (var key in result) {
if (!result.hasOwnProperty(key)) continue;
var obj = result[key];
for (var prop in obj) {
if (!obj.hasOwnProperty(prop)) continue;
alert(prop + " = " + obj[prop]);
}
}
答案 0 :(得分:0)
如果将函数作为递归函数而不是嵌套的for in
语句处理,那会更好,所以你只需要验证你的value
是否一个对象再次调用该函数,所以在代码你有这个:
var json = {
"key1": "value1",
"key2": "value2",
"key3": {
"sub_1_key1": "subvalue1",
"sub_1_key2": "subvalue2",
"sub_1_key3": "subvalue3",
"sub_1_key4": {
"sub_2_key1": "sub_2_value1"
}
},
};
var logger = document.getElementById('logs');
function goThroughJSON(json) {
for (var attr in json) {
var value = json[attr];
if (typeof value === 'object' && !(attr instanceof Array)) {
return goThroughJSON(value);
}
logger.innerHTML += attr + '<br>'
}
}
goThroughJSON(json);
&#13;
<div id="logs"></div>
&#13;
我真的希望你能帮到它。
答案 1 :(得分:0)
您可以使用递归方法。对于任何键,如果它包含对象值,您可以再次再次调用相同的函数。
const data = [{ "branch_id": 992, "sale_id": 24422, "identifier": "", "emitter": { "id": 68, "tax_id": "", "address": { "street": "Carretera a buenavista km 21", "country_code": "MEX", } } } ];
const ObjectKey = o => {
Object.keys(o).forEach(k => {
if(typeof o[k] === 'object'){
ObjectKey(o[k]);
} else {
console.log(k, " ", o[k]);
}
});
}
data.forEach(o => {
ObjectKey(o);
});
答案 2 :(得分:0)
我在这里找到了答案。
Get all keys of a deep object in Javascript
function getDeepKeys(obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
if (typeof obj[key] === "object") {
var subkeys = getDeepKeys(obj[key]);
keys = keys.concat(subkeys.map(function (subkey) {
return key + "." + subkey;
}));
}
}
return keys;
}
var data = [{ "branch_id": 992, "sale_id": 24422, "identifier": "", "emitter": { "id": 68, "tax_id": "", "address": { "street": "Carretera a buenavista km 21", "country_code": "MEX", } } }];
console.log(getDeepKeys(data));