Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add property name in JS via using push?

The below js snippet runs successfully. But if I try to not use any function; like addingTOobject_a used below; my program fails to run…

SUCCESSFUL SNIPPET ->

let a = [];

function addingTOobject_a(x, y){
    a.push({x, y});
}

console.log(a);

addingTOobject_a(["be", "happy"], false);
addingTOobject_a(["stay", "pretty"], true);
addingTOobject_a(["he", "is", "me"], false);

console.log(a);

UNSUCCESSFUL SNIPPET ->

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let a = [];

a.push({x,y});

console.log(a);

a.push(["be", "happy"], false);
a.push(["stay", "pretty"], true);
a.push(["he", "is", "me"], false);

console.log(a);

>Solution :

You need to define values for x and y somewhere.

If you aren’t going to define x and y variables and then use them as shorthand properties in your object, then you need to define them at the same time as you define the object.

a.push({ 
    x: ["be", "happy"], 
    y: false
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading