Sandra Schlichting
Sandra Schlichting

Reputation: 26046

Creating hash of hash on the fly?

I'd like to be able to create a hash of hash, but when I do

var checkState = {}
for (let i in ['a','b','c']) {
  checkState[i]          = null
  checkState[i]['state'] = null
}

console.log(checkState)

I get

(node:27532) UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'state' of undefined

For some reason checkState[i] is ok, but checkState[i]['state'] is not.

Question

Can anyone explain how I can create a hash of hash?

Upvotes: 0

Views: 100

Answers (3)

TechnoTech
TechnoTech

Reputation: 799

Things to note down

var checkState = {}
for (let i in ['a','b','c']) {
  checkState[i]          = null // this line assign checkState.a = null
// so after above line object is checkState = { a : null}
  checkState[i]['state'] = null // this line now trying to access 
//state property on a which is null( undefined), so this throws error. 
}

console.log(checkState)

you need to modify your code accordingly to get rid of this

modified code

var checkState = {}
for (let i in ['a','b','c']) {
  checkState[i]          = {} // assigned an empty object
  checkState[i]['state'] = null
}

console.log(checkState)

Upvotes: 1

Nikita Madeev
Nikita Madeev

Reputation: 4380

You can use reduce for shorter recording

const checkState = ['a', 'b', 'c'].reduce((acc, key) => ({ ...acc, [key]: { state: null } }), {});

console.log(checkState);

Upvotes: 1

olkivan
olkivan

Reputation: 99

The attempt of retreiving property of null (or undefined) causes TypeError, so use an empty object instead:

for (let i in ['a','b','c']) {
  checkState[i]          = {}
  checkState[i]['state'] = null
}

Upvotes: 4

Related Questions