Welcome,
Question about correct answer from topic: Get all keys of a deep object in Javascript
I don't understand how this "getDeepKeys" function works. I know that there are a lot of threads related to this topic, but they don't give me the full answer to my question.
The details of my question are:
- piece of code on which I am testing the function:
var data2 = {
OrderMessage:{
EntityId: "ZZ-KR/00000002/2020/1",
Buyer1: {
GLN: "GLN.6340134346_Buyer_1",
},
Seller1: {
GLN: "GLN.6340134346_Seller_1",
},
},
OrderResponseMessage: {
Standard: "STANDARD_NAME",
Buyer2: {
GLN: "GLN.6340134346"
},
Seller2: {
GLN: "GLN.7690933887",
},
}
}
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 objectt = getDeepKeys(data2);
console.log(objectt);
- at the beginning the keys array is declared = []
- During the first iteration, a value is added to this array and if the value is an object, the getDeepKeys(obj[key]) function is called again in var subkeys; with another value.
- this is the first iteration and in the "keys" array I have stored the value from my "OrderMessage" object Declaring keys - first iteration
- then after calling the function, an empty key array is created again keys = [] Declaring keys - second iteration
- I don't understand at this point how this data is stored if the arra that was supposed to store it is declared in the memory again and yet the function at the very end returns correct results?
Please help me to explain.