Home > Back-end >  (Javascript)Problems pushing array data in List
(Javascript)Problems pushing array data in List

Time:11-04

Here's my code.

let mapOptions = []
let mapOption = {}

let averagelist=[1,2]

   for(let i=0; i<averagelist.length; i  ){

         mapOption.center = averagelist[i]

         mapOption.level = 3

         mapOptions.push(mapOption)

         console.log(mapOptions)
     }

In the Snippet the result comes like strange so I'll tell you what I got. From that code I wanted to get mapOptions=[{"center":1,"level":3},{"center":2,"level":3}] But the result comes like mapOptions=[{"center":2,"level":3},{"center":2,"level":3}] Where did the 1 go? I tried lots of things but can't solve this. Could anybody help me? The browser I'm using is Chrome.

CodePudding user response:

let averagelist = [1,2];
let mapOptions = averagelist.map(i=>({center: i, level: 3}));
console.log(mapOptions);

CodePudding user response:

You need to put let mapOption = {} inside for block,for your question mapOption is defined as a global variable,so it will show the value last time it set.

let mapOptions = []

let averagelist=[1,2]

for(let i=0; i<averagelist.length; i  ){
     let mapOption = {}
     mapOption.center = averagelist[i]

     mapOption.level = 3

     mapOptions.push(mapOption)
 }
console.log(mapOptions)

CodePudding user response:

Your original code is not working as you are updating the object properties values which are primitive, Which results not updating the reference of the original object but only updating the values.

To make it work, you should reassign the whole object.

Working demo as per your code :

let mapOptions = []
let mapOption = {}

let averagelist = [1, 2];

for(let i=0; i< averagelist.length; i  ){
  mapOption = {center: averagelist[i], level: 3}
  mapOptions.push(mapOption)
}

console.log(mapOptions)

Demo with optimal solution :

let averagelist = [1, 2];

const mapOptions = averagelist.map(item => ({center: item, level: 3}))

console.log(mapOptions)

  • Related