Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

output values from json array gets undefined error

20 views
Skip to first unread message

JRough

unread,
Jun 21, 2017, 5:18:52 PM6/21/17
to
I am getting undefined in console.log. What is wrong? thanks,


var data = [
{
"cityId": "574",
"cityAndState": "Allen, TX"
},
{
"cityId": "722",
"cityAndState": "Arlington, TX"
},
{
"cityId": "1736",
"cityAndState": "Carrollton, TX"
},
{
"cityId": "1737",
"cityAndState": "Dallas, TX"
},
{
"cityId": "1739",
"cityAndState": "Baltimore, MD"
},
{
"cityId": "1740",
"cityAndState": "Ann Arbor, MI"
},
{
"cityId": "1741",
"cityAndState": "Detroit, MI"
},
{
"cityId": "1742",
"cityAndState": "Royal Oak, MI"
},
{
"cityId": "1743",
"cityAndState": "Maddison Heights, MI"
}
]


var iterateData = function(data){
var ids = [];
if (data.hasOwnProperty(key)){
for (var key in data){
if( data[key].cityAndState == "Carrollton, TX" || data[key].cityAndState =="Allen, TX"){
ids.push(data[key].cityId);
console.log(ids);
}
}

}
console.log(ids);
}
iterateData(data);

Ben Bacarisse

unread,
Jun 21, 2017, 5:34:14 PM6/21/17
to
JRough <janis...@gmail.com> writes:

> I am getting undefined in console.log. What is wrong? thanks,

The console.log call should write []. The result of the overall
function call is undefined but you should know that since you wrote it.
You don't want to use key here. It gets set below, but you never get
there because this test is false.

> for (var key in data){

You are probably better off just using a counted for here.

> if( data[key].cityAndState == "Carrollton, TX" || data[key].cityAndState =="Allen, TX"){
> ids.push(data[key].cityId);
> console.log(ids);
> }
> }
>
> }
> console.log(ids);
> }
> iterateData(data);


--
Ben.

JRough

unread,
Jun 21, 2017, 6:54:20 PM6/21/17
to
Thanks, I did take out the first for in using a regular for loop. It seems like it should work but it still says undefined.
for (var i=0; i<=data.length;i++){
var obj = data[i];
for (var key in obj){
if( obj[key].cityAndState == "Carrollton, TX" || obj.cityAndState =="Allen, TX"){
ids.push(obj[key].cityAndState);
console.log(ids);
}
}
}
}

iterateData(data);

Ben Bacarisse

unread,
Jun 21, 2017, 7:45:13 PM6/21/17
to
JRough <janis...@gmail.com> writes:
<snip>
> Thanks, I did take out the first for in using a regular for loop. It
> seems like it should work but it still says undefined.

I wonder how you got from what I said to the changes you ended up making
to the code. I ask simply so that I will know what sort of thing I
might say in future to avoid whatever misunderstanding led to your mking
the code worse.

Maybe part of the problem is that you did not consider exactly where I
put the remarks. You seem to quote everything and put a remark at the
end, whereas I put my remarks next to the part of the message to which
they applied.

<snip>
--
Ben.
0 new messages