Reputation: 1337
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]);
});
Upvotes: 1
Views: 70
Reputation: 32165
Actually you have several problems in your current code:
userinfo[user]
is incorrect, if you want to access user
property of userinfo
object you need to give it a string like userinfo["user"]
or just directly userinfo.user
.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])
.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