0

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
  • 1
    var selection_json_str = [] might work Commented Aug 31, 2015 at 13:09

1 Answer 1

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)
    });
}

Explanation

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

Sign up to request clarification or add additional context in comments.

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.
Is it better now? I know that push is not necessary, but I prefer to use it when I'm adding new element to array because it was made for it and it returns the length of array, so I save one line of code :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.