Home > OS >  Array.push not working in forEach loop using node js / javascript
Array.push not working in forEach loop using node js / javascript

Time:02-26

Hi I am new to node js and I am trying to make an array from an object

data.forEach((title) => {
  let array = [];

  for (var i = 0; i <= data.length; i  ) {
    array.push(title.title.charAt(0).toUpperCase()   title.title.slice(1))
  }
  console.log(array);

  //access.forEach((conf)=>{
  // conf.title
  // array
  //})
})
<script>
  let data = [{
      title: "user",
      fields: "required",
      access: "done"
    },
    {
      title: "root",
      fields: "default",
      access: "done"
    },
    {
      title: "super Admin",
      fields: "allready access",
      access: "defualt"
    },
    {
      title: "user1",
      fields: "required",
      access: "done"
    },
    {
      title: "test user",
      fields: "required",
      access: "done"
    },
  ]
</script>

As I want an array which contain all the title in it so I can use that array field inside the access.forEach method but what am getting is title but not in same array but as a different output

expected output

array = [User,Root,Super Admin,User1,Test user]

CodePudding user response:

An arrow function you pass into forEach is executed for every item in the data array so that you create a new array let array=[] for every item of your original one. You either want to declare the array outside of the function:

let array=[];
data.forEach(item => {
   array.push(item.title[0].toUpperCase()   item.title.slice(1));
})

or even better use map

let titles = data.map(item => item.title[0].toUpperCase()   item.title.slice(1))

An output in both cases will be: ["User", "Root", "Super Admin", "User1", "Test user"]

CodePudding user response:

your array varibale is in a forach loop put array varibale out side the loop and will work good

let array=[];
    data.forEach((title)=>{

   
    array.push(title.title.charAt(0).toUpperCase()   
    title.title.slice(1)) 
  }
    console.log(array);

})

  • Related