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');
}
element.push({'bg':'red'});? It's a bit unclear what you're asking. Could you be more specific?element['obj'] = 'one';--> this initialiseselement['obj']to string, and then you want to add a key/value pair to that (string)?arrayorobject?element['obj'] = 'one';create attrobjonelement, but its not account to length.element['obj'] = 'one', when you doelement['obj']['bg'] === 'undefined'it's equals to'one'['bg']. I think It has no sense.