0

here is my code pushing data to an array variable, but I am getting a blank array. what am I doing wrong?

let users = []

//looping ajax response here
for(var i = 0; i < response.length; i++ ) {
  users.push(response[i].user_name)
}

when I run console.log this is what I got

console.log(users) // Array[]
3
  • what is response.length before the loop .... though, considering the comment "looping ajax response here", your issue is probably with how you're (not) dealing with asynchronous responses Commented Feb 19, 2020 at 4:04
  • @JaromandaX console.log(response.length) // Array(31) Commented Feb 19, 2020 at 4:43
  • you are claiming that console.log(response.length) outputs Array(31)? hint: no, it doesn't Commented Feb 19, 2020 at 7:17

3 Answers 3

5

You can use the map function also of Javascript Array like below but before that you need to make sure that response has data in array type.

First we are checking response is not undefined and after that we are looping from response if response has data.

//looping ajax response here
let users = response && response.map(x => {
  return x.user_name;
});
Sign up to request clarification or add additional context in comments.

Comments

0

Seems you are missing the i variable value in response.

var response=[{user_name:'abc'},{user_name:'def'}]

let users = [];

for(var i = 0; i < response.length; i++ ) {
users.push(response[i].user_name)
}

After using this code you should get the result in users array.

Comments

0

Yes, you can easily add a new value to the existing array without using the push() method just use the ES6+ feature for array destructuring.

here is the code! very easy simple and need

var numberArray = [];
for (let index = 0; index < 10; index++) {
    numberArray = [...numberArray, index * 10]; // destructring the old array and adding new element
}
console.log(numberArray); // update array 

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.