user4756836
user4756836

Reputation: 1337

Copy object to an array

I am trying to copy an object userinfo into an array. I keep getting undefined when I try to console log the new array. Any help will be appreciated!

JS:

var JSONstring = [{
  "name": "test",
  "properties": {
    "age": "19r",
    "userinfo": {
      "city": "Dallas",
      "state": "Texas"
    }
  }
}];

$(document).ready(function() {
  var userinfo = {};
  for (var i = 0; i < JSONstring.length; i++) {
    var user = JSONstring[i].properties.userinfo;
    if (user === undefined) {
      continue;
    } else if (userinfo[user] === undefined) {
      userinfo[user] = [];
      userinfo[user].push(i);
    } else {
      userinfo[user].push(i);
    }
  }
  console.log(userinfo[0]);
});

JSFiddle Demo

Upvotes: 1

Views: 70

Answers (1)

cнŝdk
cнŝdk

Reputation: 32165

Actually you have several problems in your current code:

  • Writing userinfo[user] is incorrect, if you want to access userproperty of userinfoobject you need to give it a string like userinfo["user"] or just directly userinfo.user.
  • In the end you are trying to log userinfo[0] which is undefined because userinfo is an object and not an array you need to change it to : console.log(userinfo.user[0]).
  • If you want to store the user object in the array you should replace push(i) with push(user).

Demo:

I tried to refactor your code so it makes sense, here's what you need:

var JSONstring = [{
  "name": "test",
  "properties": {
    "age": "19r",
    "userinfo": {
      "city": "Dallas",
      "state": "Texas"
    }
  }
}];

$(document).ready(function() {
  var userinfo = {};
  for (var i = 0; i < JSONstring.length; i++) {
    var user = JSONstring[i].properties.userinfo;
    if (!user) {
      continue;
    } else if (!userinfo.user) {
      userinfo.user = [];
      userinfo.user.push(user);
    } else {
      userinfo.user.push(user);
    }
  }
  console.log(userinfo.user[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Note:

The condition in the if block if (userinfo[user] === undefined) can simply be written if(!userinfo.user)

Upvotes: 2

Related Questions