简体   繁体   中英

adding array name property to JSON object [ES5]

I have a JSON object with this structure:

{"Firstname":"john","Lastname":"doe"}

How do it change it to an array with this structure with the name 'abc'(?):

users: [{"Firstname":"john","Lastname":"doe"}]

This is I'm building my object from input values:

var obj = {};
obj.Firstname = document.getElementById("firstName").value;
obj.Lastname = document.getElementById("surname").value;
 console.log(obj);
var jsonStringObj = JSON.stringify(obj);
 console.log(jsonStringObj );

which returns:

{"Firstname":"john","Lastname":"doe"}

thanks!

You need to create new array and push the entire object.

 var x = {"Firstname":"john","Lastname":"doe"}; var newArray = []; newArray.push(x); console.log([{"Firstname":"john","Lastname":"doe"}])

You can create an object, having a key of user and a value of an array, having your item:

var jsonStringObj = {user: [JSON.stringify(obj)]};

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