Reputation: 41
I'm trying to push data into empty but its returning empty array. I'm trying push in json format. Push values in rows[]
Result {
command: 'SELECT',
rowCount: 2,
oid: NaN,
rows:
[ anonymous { username: 'pewdiepie' },
anonymous { username: 'tseries' } ],
Code:
var newList = new Array();
data => {
for(var i = 0; i< data.length; i++){
newList.push(data.rows[i].username)
}}
Upvotes: 1
Views: 1990
Reputation: 781058
i < data.length
should be i < data.rows.length
. data
is the container object, data.rows
is the array you're looping through.
But instead of a loop you can use map
:
newList = data.rows.map(e => e.username);
or forEach
data.rows.forEach(e => newList.push(e.username));
Upvotes: 1
Reputation: 3066
There's just one error buddy. The for
loop should range from 0
to length of rows
inside the object. But you are doing [object].length. Hence it isn't giving the right output.
Here is the working code:
var data = {
command: 'SELECT',
rowCount: 2,
oid: NaN,
rows: [
anonymous = {
username: 'pewdiepie'
},
anonymous = {
username: 'tseries'
}
]
}
var newList = new Array();
for (var i = 0; i < data.rows.length; i++) {
newList.push(data.rows[i].username);
}
console.log(newList);
Upvotes: 0