Reputation: 73
I have this object structure that I want to iterate through to make a node of all the "properties." So I want to make nodes for the objects 1,2,5, and 8 but not for the arrays. I have this piece of code and was wondering why Object.keys() for each of response's properties is [0] instead of [2,5] or [9,12]?
const response = {
'1':{
'2':['3','4'],
'5':['6','7']
},
'8':{
'9':['10','11'],
'12':['13','14']
},
};
for(const property in response){
if(!response.hasOwnProperty(property)) continue;
console.log(property) // prints 1 and 8
g.addNode(property);
console.log(Object.keys(property)) // [0] instead of [2,5] or [9,12]
for(const prop in property){
if(!property.hasOwnProperty(prop) || prop === 0) continue;
console.log(prop)
g.addEdge(prop,property, {directed:true})
}
}
EDIT: this loop works :)
for(const property in resp){
g.addNode(property);
for(const prop in resp[property]){
g.addEdge(property,prop, {directed:true})
}
}
Upvotes: 0
Views: 56
Reputation: 286
I've run into this exact issue with dictionaries, and it's good you're running into this issue relatively quickly because it can get pretty hard to debug once you get further. Basically, you're iterating over a dictionary with a for..in
loop, which doesn't exactly do what you want it to. Basically, each item you iterate over (property
in this case) isn't the value of the dictionary ({'2':['3','4'], '5':['6','7']}
), it's a full dictionary item that includes both key and value. This is practically useless to you, so it's not particularly helpful. There are a couple things you can do, one of which still uses a forEach, except somewhat differently:
Object.keys(response).forEach(function(key) {
// do your actions here
// key is your dictionary key (1, 8)
// response[key] will have your value ({'2':['3','4'], '5':['6','7']})
});
This should work, and you can put the rest of your code to use this.
Upvotes: 1