Home > Software engineering >  How to push item to not existing object key
How to push item to not existing object key

Time:11-13

I want to create object of arrays but when i run below code it gives

TypeError: Cannot read property 'push' of undefined

How can i push something to not existing array?

const obj = {}

someArray.forEach(key => {
    anotherArray.forEach(key2 => {
        obj[key].push(key2)
    })
})

CodePudding user response:

Here obj is an empty array , it does not have key property. So before pushing you can check if it has the property , if not then you can create and then push

const obj = {}

someArray.forEach(key => {
  anotherArray.forEach(key2 => {
    if (!obj[key]) {
      obj[key] = []
    }
    obj[key].push(key2)
  })
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related