0

Good day!

I'm not quite exposed with client-side scripting like javascript so I wanted to learn how to assign or even add sets of values to a javascript variable array. I understand that if you have to assign values manually it looks like this

var data = [{
            name: 'charlie',
            com:'lkdhls dfjgldkg kfldg kdlfngldlf',
            id: 1
        }, {
            name: 'mark',
            com: 'lkdhls dfjgldkg kfldg kdlfngldlf erttre',
            id: 2
        }, {
            name: 'darrell',
            com: 'lkdhls dfjgldkg kfldg ',
            id: 3
        }, {
            name: 'rick',
            com: 'lkdhls dfjgldkg kfldg kdlfngldlf',
            id: 4
        }, {
            name: 'heather',
            com: 'lkdhls dfjgldkg kfldg kdlfngldlf ertwtrrb ryryre',
            id: 5
        }];

Now my question is, how do I assign or add values to this var data = []; coming from my json result like this?

          var data =[];

            $.getJSON('/controller/method', null, function (result) {

           // from here I want to insert the result to data variable so I can call it to my next function
            });

How do I do this? Thanks...

6
  • 1
    Use push(): developer.mozilla.org/en/docs/Web/JavaScript/Reference/…. Although, can you not amend the returned JSON to be in that format? Jun 3, 2015 at 8:02
  • 1
    unshift() can also be used, based on where data should be added. Also based on what the result is you will need to do some extra manipulations with it.
    – Stepashka
    Jun 3, 2015 at 8:04
  • 1
    Adding to @rory comment, data.push.apply(data , result) or data = data.concat(result);
    – Satpal
    Jun 3, 2015 at 8:06
  • 1
    @timmack how does result look like?? it should be already array, you can simple assign data = result
    – ozil
    Jun 3, 2015 at 8:06
  • Thanks for all your comment but after assigning the json results to the variable array. Can we also call that variable in the other functions holding the values of the same json results that were assigned?
    – timmack
    Jun 3, 2015 at 8:31

0

Your Answer

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

Browse other questions tagged or ask your own question.