Reputation: 839
I have an array of maps with several values that I need to discard while keeping the map format.
I've played with the Arrays.map() function, but I only get to reach an array of values, without the map anymore.
The code would be:
x=[{"id":1, "name":"Bob"}, {"id":2, "name":"Sam"}, {"id":3, "name":"Lucy"}];
And the expected result I need is:
result=[{"id":1}, {"id":2}, {"id":3}]
What I tried:
>> result= x.map(x => x.id);
<< result = [1, 2, 3]
I am sure this must be extremely straightforward, but I'm struggling to pull this one off, can I get some advice?
Upvotes: 2
Views: 2734
Reputation: 33726
In your approach, you're extracting the id value, however, you're not generating key-value
objects.
You can use the function map
and destructuring the param in order to extract the id
value.
let x=[{"id":1, "name":"Bob"}, {"id":2, "name":"Sam"}, {"id":3, "name":"Lucy"}];
let result = x.map(({id}) => ({id}));
console.log(result);
.as-console-wrapper { min-height: 100%; }
Upvotes: 5