I want to create an Array of Objects as given below
var selection_json_str=[
{
"idx":0,
"fieldname":"%Key0",
"fieldvalue": [
"05-5003",
"05-5005",
"06-6007",
"06-6009"]
},
{
"idx":1,
"fieldname":"%Key1",
"fieldvalue": [
"5003",
"5005",
"6007",
"6009"]
},
{
"idx":2,
"fieldname":"%Key2",
"fieldvalue":[
"1",
"1"]
}
]
var noCols = _this.Data.HeaderRows[0].length;
var selection_json_str = {}
for (var c = 0; c < noCols; c++) {
var t = [];
var a = []
for (var r = 0; r < _this.Data.Rows.length; r++) {
a.push(_this.Data.Rows[r][c].text);
}
//ConsoleInfo(a);
//ConsoleInfo(GetUnique(a)); Get Unique Key from the list
selection_json_str[c] = {
idx: c,
fieldname: _this.Data.HeaderRows[0][c].text,
fieldvalue:GetUnique(a)
};
}
I have a code which I have to change to get the above output , can any one help me out here . I need to have array of objects within selection_json_str . Can any help me out ?
1 Answer 1
Try:
var selection_json_str = new Array();
for (var c = 0; c < noCols; c++) {
var t = [];
var a = []
for (var r = 0; r < _this.Data.Rows.length; r++) {
a.push(_this.Data.Rows[r][c].text);
}
//ConsoleInfo(a);
//ConsoleInfo(GetUnique(a)); Get Unique Key from the list
selection_json_str.push({
idx: c,
fieldname: _this.Data.HeaderRows[0][c].text,
fieldvalue:GetUnique(a)
});
}
A bit extra explanation:
I've changed selection_json_str to new Array() that we will know what kind of data will be there. And when I add a new element I just call selection_json_str.push(element). It's not necessary to call push, but I prefer to do it when I'm adding something to array. It gives a better understanding of code. (IMHO)
After our loop is done we'll have array of objects in selection_json_str
2 Comments
push is not necessary here, the bracket notation used in OP code is fine too. Also it would be better to explain what changes you've made, instead of copy pasting a sample of code.
var selection_json_str = []might work