I have the following object
JavaScript
x
6
1
calendarLists = [
2
{Title: titel1, Color:blue, number:1}
3
{Title: titel2, Color:green, number:2}]
4
{Title: titel3, Color:red, number:3}
5
]
6
It has alot more property but for simplicity sake ill just show 3 properties. I also have the follow array [Title,number]
Now basing from the array I only want to show object property based on my array. My results should be
JavaScript
1
2
1
results =[{Title: titel1, , number:1},{Title: titel2, , number:2},{Title: titel3, , number:3}]
2
Advertisement
Answer
You could map the wanted properties as objects, collect them to a single object and mapp all objects for a new array.
JavaScript
1
9
1
var calendarLists = [
2
{ Title: 'titel1', Color: 'blue', number: 1 },
3
{ Title: 'titel2', Color: 'green', number: 2 },
4
{ Title: 'titel3', Color: 'red', number: 3 }
5
],
6
keys = ['Title', 'number'],
7
result = calendarLists.map(o => Object.assign(keys.map(k => ({ [k]: o[k] }))));
8
9
console.log(result);
The same with a destructuring assignment and short hand properties.
JavaScript
1
8
1
var calendarLists = [
2
{ Title: 'titel1', Color: 'blue', number: 1 },
3
{ Title: 'titel2', Color: 'green', number: 2 },
4
{ Title: 'titel3', Color: 'red', number: 3 }
5
],
6
result = calendarLists.map(({ Title, number }) => ({ Title, number }));
7
8
console.log(result);