1

I have problem with array Objects. I have variable "setting". If I write:

var settings=[];
var tempSettings=[{
   id:1,
   name:"Test1"
  },
  {
    id:2,
    name:"Test2"
   }
];
settings=tempSettings;
console.log(settings[0]);

All right-all work. settings[0]- no problem;

But if I received data from file and do:

 jQuery.getJSON("myurl", function(data) {
console.log(data);                  
var zones=data.split("~");          
jQuery.each(zones, function(key, value) {
          var set = value.split(",");
          var tset={
                  id:set[0],
                  name:set[1]
               };

          settings.push(tset);         
    }); 
});
console.log(settings[0]);   

This not work settings[0] - undefined. What my mistake?

Data I received and console.log(data); get me string data.

Added:

console.log(tempSettings) in variant hardcodded does:

[Object { Id=1, name="Test1"},Object { Id=2, name="Test2"} ]

and console.log(settings) in received variables does: [].

but in after click in console I see:

[0] Object { id="3", name="Test3"}, [1] Object { id="4", name="Test4"}.

8
  • It's likely that whatever data you're splitting on ~ does not have anything to iterate over. I would inspect what's in data to make sure it has something you expect. Commented Jun 20, 2014 at 15:32
  • Do you have a sample of data that you receive from the server? Commented Jun 20, 2014 at 15:32
  • I can only presume that what you're returning from your server is not valid JSON. The data passed to the callback of .getJSON should be an object, not a string. Commented Jun 20, 2014 at 15:32
  • You're missing the closing }); from your getJSON in that code btw. Commented Jun 20, 2014 at 15:32
  • what does console.log(set[0]); and console.log(set[1]); output? also, jQuery.getJSON is not closed properly Commented Jun 20, 2014 at 15:32

1 Answer 1

1

getJSON is asynchronous. You need to include the console.log within the callback function:

jQuery.getJSON("myurl", function(data) {
  console.log(data);
  var zones=data.split("~");
  jQuery.each(zones, function(key, value) {
    var set = value.split(",");
    var tset = {
      id:set[0],
      name:set[1]
    };
    settings.push(tset);         
  });
  console.log(settings[0]);
});
Sign up to request clarification or add additional context in comments.

1 Comment

console.log(tempSettings) in variant hardcodded does: [Object { Id=1, name="Test1"},Object { Id=2, name="Test2"} ] and console.log(settings) in received variables does: []. but in after click in console I see: [0] Object { id="3", name="Test3"}, [1] Object { id="4", name="Test4"}.

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.