Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  85] [ 6]  / answers: 1 / hits: 45263  / 6 Years ago, tue, december 11, 2018, 12:00:00

I have an array of Object as follows:


var obj = [
{a: 1, b: 5, c: 9},
{a: 2, b: 6, c: 10},
{a: 3, b: 7, c: 11},
{a: 4, b: 8, c: 12}
];

I know about how to get single object using Array.map() like this.


var result = obj.map(x=>x.a)

This will give me following result


[1, 2, 3, 4]

But I want result like follows:


[
{a: 1, b: 5},
{a: 2, b: 6},
{a: 3, b: 7},
{a: 4, b: 8}
]

In short, from an array of objects I want to select only a few fields (more than one).


How can I do that?


More From » arrays

 Answers
13

You can use .map() with Object Destructuring:





let data = [
{a:1,b:5,c:9}, {a:2,b:6,c:10},
{a:3,b:7,c:11}, {a:4,b:8,c:12}
];

let result = data.map(({ a, b }) => ({a, b}));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




[#52944] Wednesday, December 5, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;