Skip to content
Advertisement

Is there a way to only show selected property in a json object based on a array

I have the following object

calendarLists = [
    {Title: titel1, Color:blue, number:1}
    {Title: titel2, Color:green, number:2}]
    {Title: titel3, Color:red, number:3}
]

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

results =[{Title: titel1, , number:1},{Title: titel2, , number:2},{Title: titel3, , number:3}]

Advertisement

Answer

You could map the wanted properties as objects, collect them to a single object and mapp all objects for a new array.

var calendarLists = [
  { Title: 'titel1', Color: 'blue', number: 1 }, 
  { Title: 'titel2', Color: 'green', number: 2 }, 
  { Title: 'titel3', Color: 'red', number: 3 }
],
keys = ['Title', 'number'],
result = calendarLists.map(o => Object.assign(...keys.map(k => ({ [k]: o[k] }))));

console.log(result);

The same with a destructuring assignment and short hand properties.

var calendarLists = [
  { Title: 'titel1', Color: 'blue', number: 1 }, 
  { Title: 'titel2', Color: 'green', number: 2 }, 
  { Title: 'titel3', Color: 'red', number: 3 }
],
   result = calendarLists.map(({ Title, number }) => ({ Title, number }));

console.log(result);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement