TypeScript过滤器数组(按元素名称)

时间:2018-12-13 19:23:57

标签: typescript

我的模型数组如下:

 records: [{
            "idPartner": 2,
            "name": "partner1",
            "orgAddress1": "",
            "orgAddress2": null,
            "city": "Dorval",
            "postCode": "H9P 2V4",
            "state": "QC",
            "country": "CA",
            "province": null,
            "description": null
        },
        {
            "idPartner": 3,
            "name": "partner12",
            "orgAddress1": "",
            "orgAddress2": null,
            "city": "Dorval",
            "postCode": "H9P 2V4",
            "state": "QC",
            "country": "CA",
            "province": null,
            "description": null
        }
]

我需要创建一个名称仅为["partner1", "partner12"]

的新数组

如何使用打字稿来做到这一点?

2 个答案:

答案 0 :(得分:1)

不需要Array.from或整个花括号混乱:

records.map(x => x.name);

答案 1 :(得分:0)

我将为您推荐2种解决方案。

地图

records = [{
    "idPartner": 2,
    "name": "partner1",
    "orgAddress1": "",
    "orgAddress2": null,
    "city": "Dorval",
    "postCode": "H9P 2V4",
    "state": "QC",
    "country": "CA",
    "province": null,
    "description": null
  },
  {
    "idPartner": 3,
    "name": "partner12",
    "orgAddress1": "",
    "orgAddress2": null,
    "city": "Dorval",
    "postCode": "H9P 2V4",
    "state": "QC",
    "country": "CA",
    "province": null,
    "description": null
  }
]

console.log(records.map(x => x.name))

Array.from()

作为第二个选项,使用Array.from并返回name。它将仅使用name创建和排列。

records = [{
    "idPartner": 2,
    "name": "partner1",
    "orgAddress1": "",
    "orgAddress2": null,
    "city": "Dorval",
    "postCode": "H9P 2V4",
    "state": "QC",
    "country": "CA",
    "province": null,
    "description": null
  },
  {
    "idPartner": 3,
    "name": "partner12",
    "orgAddress1": "",
    "orgAddress2": null,
    "city": "Dorval",
    "postCode": "H9P 2V4",
    "state": "QC",
    "country": "CA",
    "province": null,
    "description": null
  }
]

console.log(Array.from(records, (obj)=>{return obj.name}))