Reputation: 29
I've a newbie on object programming. I was logging an object to the Chrome console and couldn't fail to notice a weird behavior.
Some properties appear as undefined at the bottom of the log, but have value on top.
When I return the object from my function it returns with those same properties defined, therefore Dirty Sock
and Microphone
are defined. So why does the console think they are not?
My code:
function updateInventory(arr1, arr2) {
let currentInv = array2DToObject(arr1);
let newItems = array2DToObject(arr2);
console.log(currentInv); //This is the log I'm speaking about.
for(let key in currentInv) {
if(newItems.hasOwnProperty(key)) {
currentInv[key] = currentInv[key] + newItems[key];
delete newItems[key];
} else {
currentInv[key] = newItems[key];
delete newItems[key];
}
}
if(Object.keys(newItems === 0) && newItems.constructor === Object) {
return currentInv;
} else {
return 'A mistake has occured, newItems obj has not been emptied correctly';
}
function array2DToObject (arr) {
return arr.reduce((acc, curr) => {
acc[curr[1]] = curr[0] ;
return acc;
}, {});
}
}
Values for arr1
and arr2
are as follow:
arr1 = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
arr2 = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
Upvotes: 0
Views: 596
Reputation: 36
The information box at the end of your console.log output (in the Chrome console) is likely to state that the output has just been recalculated. If you want to know the state of your objects at the time of outputting, I would suggest creating a string first and then outputting. In your example, try:
console.log(JSON.stringify(currentInv));
And then see what happens.
Upvotes: 2