开发者问题收集

过滤数组并形成新数组

2019-12-29
62

目前我有如下数据:

[ 
        { 
           "integration_id":7,
           "campaign_id":4,
           "integration_name":"unbounce",
           "url_string":"23432fsaf",
           "created_at":"2019-12-23 21:05:45",
           "updated_at":"2019-12-23 21:05:45"
        },
        { 
           "integration_id":37,
           "campaign_id":4,
           "integration_name":"clickfunnels",
           "url_string":"yttzbe9rwd",
           "created_at":"2019-12-27 19:19:02",
           "updated_at":"2019-12-27 19:19:02"
        },
        { 
           "integration_id":47,
           "campaign_id":4,
           "integration_name":"instapage",
           "url_string":"vaqcjq8iy2",
           "created_at":"2019-12-29 16:52:01",
           "updated_at":"2019-12-29 16:52:01"
        }
]

但我想将此数组转换为如下数组:

[
        { 
           "integration_name":"unbounce",
        },
        { 
           "integration_name":"clickfunnels",          
        },
        {  
           "integration_name":"instapage",            
        }
 ]

我想保留集成名称,但删除项目中的所有其他属性。我该如何实现?

2个回答

您可以简单地对数据执行 .map() ,然后使用 解构赋值 仅返回 integration_name 键/值>

const data = [{
    "integration_id": 7,
    "campaign_id": 4,
    "integration_name": "unbounce",
    "url_string": "23432fsaf",
    "created_at": "2019-12-23 21:05:45",
    "updated_at": "2019-12-23 21:05:45"
  },
  {
    "integration_id": 37,
    "campaign_id": 4,
    "integration_name": "clickfunnels",
    "url_string": "yttzbe9rwd",
    "created_at": "2019-12-27 19:19:02",
    "updated_at": "2019-12-27 19:19:02"
  },
  {
    "integration_id": 47,
    "campaign_id": 4,
    "integration_name": "instapage",
    "url_string": "vaqcjq8iy2",
    "created_at": "2019-12-29 16:52:01",
    "updated_at": "2019-12-29 16:52:01"
  }
];

let newArray = data.map(({integration_name}) => ({integration_name}));

console.log(newArray);
Shiny
2019-12-29

您可以将 Array.map 对象解构 结合使用。>

let input = [{ "integration_id":7, "campaign_id":4, "integration_name":"unbounce", "url_string":"23432fsaf", "created_at":"2019-12-23 21:05:45", "updated_at":"2019-12-23 21:05:45" }, { "integration_id":37, "campaign_id":4, "integration_name":"clickfunnels", "url_string":"yttzbe9rwd", "created_at":"2019-12-27 19:19:02", "updated_at":"2019-12-27 19:19:02" }, { "integration_id":47, "campaign_id":4, "integration_name":"instapage", "url_string":"vaqcjq8iy2", "created_at":"2019-12-29 16:52:01", "updated_at":"2019-12-29 16:52:01" }]

let result = input.map(({integration_name}) => ({integration_name}));

console.log(result);
mickl
2019-12-29