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

前端 未结 2 1574
北恋
北恋 2021-01-19 07:50

I have the following object

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


        
2条回答
  •  佛祖请我去吃肉
    2021-01-19 08:15

    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);

提交回复
热议问题