简体   繁体   中英

javascript can't reassignment data to array in map()


let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array.map(obj=>{
  obj = obj.levle2.data
});
console.log(obj2Array)

what I'm expecting is ["data","data","data"].But I still got the original data. I know I can use forEach() to achieve this, but why I can't reassignment element in map()?

Because .map() does not mutate the original array, it returns a new one, so you should do sth like this:

let obj2Array = [obj2,obj2,obj2];
obj2Array = obj2Array.map(obj=>{
  obj = obj.levle2.data
});
console.log(obj2Array)

You forgot to set obj2Array to the value returned by .map() . See below:

 var obj2 = { level2:{ data:"data" } } var obj2Array = [obj2,obj2,obj2]; // set to returned map obj2Array = obj2Array.map(obj=>{ return obj2.level2.data }); console.log(obj2Array)

Map will return new array

const result = obj2Array.map(obj=>{
  return obj2.levle2.data
});
console.log(result)

the map() method creates a new array populated with the results of calling a provided function on every element in the calling array. as this says in the documentation you can reAssign the obj2Array when doing map

like this

let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array = obj2Array.map(obj=>{
  return obj.level2.data
});

console.log( obj2Array )
// now it is ["data","data","data"];

map() returns a new array. Try this code:

let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array = obj2Array.map(obj=>
  obj.level2.data
);

console.log( obj2Array )

output ["data", "data", "data"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM