Teyyihan Aksu
Teyyihan Aksu

Reputation: 156

How to push array to object that doesn't exist in object?

I'm very new to JavaScript. I was trying pushing new values to an object. But when I tried to push an array that doesn't exist in myObj, I got Cannot read property 'push' of undefined error. My code is below:

var myObj = {
    first: "first value",
    second: "second value",
}

myObj.third.push(123)

console.log(myObj)

But when I check if it doesn't exist and create an empty array, then push it, it works. =>

var myObj = {
    first: "first value",
    second: "second value",
}

myObj['third'] = myObj.third || []

myObj.third.push(123)

console.log(myObj)

I wonder if bottom code is best practice and if there is a better way to do it.

Upvotes: 0

Views: 1261

Answers (2)

Wilhelmina Lohan
Wilhelmina Lohan

Reputation: 3043

Updated 2nd:

You could do a ternary operator

let myObj = {
  first: 'first value',
  second: 'second value'
};

myObj.third = myObj.third ? [...myObj.third, 123] : [123];

console.log(myObj);

Upvotes: 1

Crisoforo Gaspar
Crisoforo Gaspar

Reputation: 3830

The push method is part of the Array prototype in your particular case you are trying to access a not defined property which in JavaScript is consider undefined so you are trying to do transalates into something like:

myObj.third.push => myObj.undefined.push

Because myObj does not have a third key you can try this in the console doing console.log(myObje.third );

So the engine returns an error saying that undefined does not have a property push that is only available in Array.

In this case you need to set assign a value to myObj.third before using it as an array, for that there are multiple ways to set the value as an array your answer above is one of those ways:

myObj['third'] = myObj.third || []

That line works however if for example myObj.third has a value will use that as a value as you are assigning the result of the operation myObj.third || [] which in this scenario anything that evaluates as truthy will be returned if for instance you have:

myObj.third = true; 

And then you do:

myObj.third.push(123);

An error will be displayed Uncaught TypeError: myObj.third.push is not a function as currently myObj.third is not an array.

So you need to make sure you are operating over an Array when using push, or at least when you initialize the value of your property is set as an Array, you can find more details on Array construction on this page.

Alternatives you can do to check before pushing are:

if ( ! Array.isArray(myObj.third) ) {
   myObj.third = [];
}

myObj.third.push(123)

Upvotes: 1

Related Questions