简体   繁体   中英

how to push the key value in empty object using es6

how to push the empty key value in empty object using es6

const obj={};

First I need to check the object is isEmpty or not then I need to push the key and value in that object.

if(Object.keys(obj).length === 0) {
   const contArry = {"name": "xxx", "age": "0"};
}

i tried it but not working for me

My output must be obj={"name": "xxx", "age": "0"}

You could use Object.assign .

 const obj = {}; if (!Object.keys(obj).length) { Object.assign(obj, { name: "xxx", age: "0" }); } console.log(obj);

You could use Object.assign:

 if(Object.keys(obj).length === 0) {
    Object.assign(obj, {"name": "xxx", "age": "0"});
 }

or just:

 if(Object.keys(obj).length === 0) {
     obj.name = "xxx";
     obj.age" = "0";
 }

how to push the key value in empty object

var emp = {};
emp.name = "Steven";
emp.std = "12";
emp.sub = "CS";
emp.school = "LF"
console.log(emp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM