Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript check if array object exists or undefined

How do I add push a new object into the array if it doesn't exist?

I check this link: How to check if array element exists or not in javascript?

but not sure how to push the new object though!

var element = [];

element['obj'] = 'one';

if (typeof element['obj']['bg'] === 'undefined') {

  console.log('not defined');

  element['obj']['bg'] = 'red';

  console.log(element);

} else {
  console.log('defined');
}
like image 601
tonoslfx Avatar asked Jul 21 '26 17:07

tonoslfx


1 Answers

var element = []; defines an array and not an object. To push a new value into an array you need to use the push method :

element.push({'obj' : 'one'});

But I think you do not need to create an array here, but just create an object. Declare your object like var element = {};

Like this the line element['obj'] = 'one'; works, you have an object with the key obj and the value one.

When you write element['obj']['bg'] you try to access on an object inside an object. So before set the value red into you need create the object :

element['obj'] = {};
element['obj']['bg'] = 'red';

Full example :

var element = {};

element['obj'] = {};

if (typeof element['obj']['bg'] === 'undefined') {

  console.log('not defined');

  element['obj']['bg'] = 'red';

  console.log(element);

} else {
  console.log('defined');
}
like image 79
R3tep Avatar answered Jul 24 '26 06:07

R3tep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!