2

I need to take an array objects that and map it so that the new array is just a simple array if each object's id.

So for example:

[
    {id: 49, name: "Rest update test"},
    {id: 12, name: "Rest test"}
]

would become:

[49, 12]

i have tried this so far:

myObject.map(object => object.id);

so my actual function that is not working is the following, when I view the console.log, it is showing the original object:

onSubmit() {
    this.userForm.value.accountsToAdd.map(object => object.id);
    console.log(this.userForm.value.accountsToAdd);
}
4
  • 1
    what does not work with that approach? Commented Mar 15, 2018 at 19:50
  • Could it be that you're missing a comma in your array definition? That map statement works fine as long as the map function is supported. In older browsers you need to use a for loop Commented Mar 15, 2018 at 19:52
  • You are missing a comma after the first object. Commented Mar 15, 2018 at 19:52
  • not the comma, sorry that is just a copy and past out of the console.log I forgot the comma in the post Commented Mar 15, 2018 at 19:54

1 Answer 1

5

Assuming the given code does not work, then you need to assign the result of mapping.

Array#map does not mutate the original array but return a new one.

var array = [{ id: 49, name: "Rest update test" }, { id: 12, name: "Rest test" }],
    ids = array.map(object => object.id);

console.log(ids);

Sign up to request clarification or add additional context in comments.

2 Comments

I added the function I am calling this in, as you can see. so do i need to reassign this.userForm.value.accountsToAdd to a variable within the function scope first?
map returns a new array and you need to assign it somwhere.

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.