0

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()?

1
  • 2
    there is a syntax error its obj.level2.data not obj2.levle2.data Commented Feb 17, 2020 at 7:07

5 Answers 5

1

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

Comments

0

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)

Comments

0

Map will return new array

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

Comments

0

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"]

Comments

0

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"];

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.