0

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 objects properties appear as undefined and as if they had values at the same time

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"] ]; 
3
  • What is the value of arr2 that you're passing in? Commented Jul 27, 2017 at 19:26
  • @Kevin Values for arr1 and arr2 added to the question Commented Jul 27, 2017 at 19:47
  • It looks like your error is in the names. Notice Hair Pin and Bowling Ball have values and are the two common names between the arrays. The arrays can't implicitly make a connection between "Half-Eaten Apple" and "Dirty Sock" or "Microphone" Commented Jul 27, 2017 at 19:49

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.