I have some problem creating an object array 2d with javascript (no jquery)
the output should be some one of this:
{"Switch":[{"name":"Switch 1","description":"Switch 1"},{"name":"Switch 2","description":"Switch 2"},{"name":"Switch 3","description":"Switch 3"},{"name":"Switch 4","description":"Switch 4"},{"name":"Switch 5","description":"Switch 5"},{"name":"Switch 6","description":"Switch 6"},{"name":"Switch 7","description":"Switch 7"}]}
the only one goal I reach is using two different arrays, one for the name and one for the description, doing someting like this:
var swName = [];
var swDesc = [];
var i;
var namePrefix = "swtchname";
var descPrefix = "swtchdesc";
var count = document.querySelectorAll('[id^="swtchname"]').length; //if exist swtchname exist olso description
for(i=0;i<count;i++){
var name;
var desc;
name = document.getElementById(namePrefix + i).value;
desc = document.getElementById(descPrefix + i).value;
swName.push(name);
swDesc.push(desc);
}
I would like to create an object with two-dimension and put all the data in it.
How can I change this? cause if I create an object like this, it should be easy also print the JSON format, right?
Assuming you have <input>
elements with swtchname{x}
and swtchdesc{x}
as id
where x
is a number, try something like:
var namePrefix = "swtchname"; var descPrefix = "swtchdesc"; var names = document.querySelectorAll('[id^="swtchname"]'); var X = { Switch: [] }; names.forEach(function(i) { var desc = document.getElementById(i.id.replace(namePrefix, descPrefix)); X.Switch.push({ name: i.value, desc: (desc && desc.value) || '' }); }); console.log(X);
<input id="swtchname1" value="name 1"> <input id="swtchdesc1" value="desc 1"> <input id="swtchname2" value="name 2"> <input id="swtchdesc2" value="desc 2"> <input id="swtchname3" value="name 3"> <input id="swtchdesc3" value="desc 3"> <input id="swtchname4" value="name 4"> <input id="swtchdesc4" value="desc 4"> <input id="swtchname5" value="name 5"> <input id="swtchdesc5" value="desc 5"> <input id="swtchname6" value="name 6"> <input id="swtchdesc6" value="desc 6">
Yeah after a lot of try I found my way:! I did a thing like this:
var SWarr = [];
for (var i = 0; i < count; i++) {
SWarr.push({
name: document.getElementById(namePrefix + i).value,
description: document.getElementById(descPrefix + i).value,
});
}
var jsonFormInfo = (JSON.stringify({ Switch: [SWarr] }));
Thank a lot for the input!
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.