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

前端 未结 2 1546
北恋
北恋 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);

    0 讨论(0)
  • 2021-01-19 08:30

    Your calendarLists has syntax error. You can map this array and filter wanted properties.

    calendarLists = [{
        Title: 'titel1',
        Color: 'blue',
        number: 1
      },
      {
        Title: 'titel2',
        Color: 'green',
        number: 2
      },
      {
        Title: 'titel3',
        Color: 'red',
        number: 3
      }
    ];
    
    result = calendarLists.map(
      calendarList => {
        return {
          Title: calendarList.Title,
          number: calendarList.number
        }
      }
    );
    
    console.log(result);
    
    0 讨论(0)
提交回复
热议问题