1

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)
       }}
2
  • 3
    It should be data.rows.length, not data.length. Commented Dec 3, 2018 at 9:36
  • Got it thanks!!!!!! Commented Dec 3, 2018 at 9:38

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

4 Comments

I tried using forEach it didn't work.I don't know why?
Since I can't see your code, I don't know why either. I've added a forEach example to my answer.
Got my mistake, I didn't use data,rows, I directly went for data.forEach
That's the same problem you made in your for loop, which I pointed out in the first line of the answer.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.