将数组名称 属性 添加到 JSON 对象 [ES5]
adding array name property to JSON object [ES5]
我有一个具有这种结构的 JSON 对象:
{"Firstname":"john","Lastname":"doe"}
如何将其更改为具有名称 'abc'(?) 的结构的数组:
users: [{"Firstname":"john","Lastname":"doe"}]
这是我根据输入值构建我的对象:
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 );
哪个returns:
{"Firstname":"john","Lastname":"doe"}
谢谢!
您需要创建新数组并推送整个对象。
var x = {"Firstname":"john","Lastname":"doe"};
var newArray = [];
newArray.push(x);
console.log([{"Firstname":"john","Lastname":"doe"}])
您可以创建一个对象,具有用户键和数组值,并具有您的项目:
var jsonStringObj = {user: [JSON.stringify(obj)]};
我有一个具有这种结构的 JSON 对象:
{"Firstname":"john","Lastname":"doe"}
如何将其更改为具有名称 'abc'(?) 的结构的数组:
users: [{"Firstname":"john","Lastname":"doe"}]
这是我根据输入值构建我的对象:
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 );
哪个returns:
{"Firstname":"john","Lastname":"doe"}
谢谢!
您需要创建新数组并推送整个对象。
var x = {"Firstname":"john","Lastname":"doe"};
var newArray = [];
newArray.push(x);
console.log([{"Firstname":"john","Lastname":"doe"}])
您可以创建一个对象,具有用户键和数组值,并具有您的项目:
var jsonStringObj = {user: [JSON.stringify(obj)]};