GMB
GMB

Reputation: 41

Not able to push data in empty array in js

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

Answers (2)

Barmar
Barmar

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

Harshith Rai
Harshith Rai

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

Related Questions