简体   繁体   中英

Add multiple key value pairs in a JavaScript object

I want a JavaScript object which should have multiple key values pairs. However, I am unable to add. On clicking a function, I am getting multiple key value pairs as

{id:"1" ,desc: "first"} , {id:"2", desc:"two"} , {id:"3" , desc:"three"} ...

How can I add them to the object so that the final object should look like this:

prdObj= ({id:"1" ,desc: "first"} , {id:"2", desc:"two"} , {id:"3" , desc:"three"});

Try this:

prdObj = [{id:"1" ,desc: "first"} , {id:"2", desc:"two"} , {id:"3" , desc:"three"}];

//when adding
prdObj.push( {id:"4" , desc:"four"});

You can try this with single key value:

var yourObject = [{"yourkey":"yourvalue"}, {"yourkey":"yourvalue"}];

OR

var yourObject = [{"key1":"yourvalue", "key2":"yourvalue"}, {"key1":"yourvalue", "key2":"yourvalue"}];

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