使用.map迭代对象以显示内部数组值

时间:2017-10-26 13:30:00

标签: javascript reactjs ecmascript-6

我有一个JSON 字符串化对象

{
  "lesseeName": "Padyster-7",
  "lesseeRegNo": "12345",
  "lesseeVatNo": "4456",
  "telFaxNo": "1234567891",
  "billingAddress": {
    "addressId": null,
    "addressLine1": "XYz , l1 street",
    "addressLine2": "near xyz bank",
    "postalCode": "60000",
    "countryName": "MY",
    "cityName": "Kuala lumpur",
    "stateProvinceCode": "Kuala lumpur"
  },
  "mlaList": [{
    "mlaNo": 92,
    "lesseeId": 108,
    "executionDate": "27/01/2017",
    "signatoryInfo": "Test",
    "overdueRate": 3.44,
    "nonPaymentDays": 2,
    "consolidationTerm": "Monthly",
    "createdBy": null,
    "createdDtm": null,
    "updatedBy": null,
    "updatedDtm": null,
    "statusIndicator": null,
    "signatoryEmail": "tooot@gmail.com",
    "leaseMlaNo": "OPM1",
    "statusDescription": "APPROVED"
  }, {
    "mlaNo": 93,
    "lesseeId": 108,
    "executionDate": "03/01/2017",
    "signatoryInfo": "tess",
    "overdueRate": 5.77,
    "nonPaymentDays": 2,
    "consolidationTerm": "Bi-Monthly",
    "createdBy": null,
    "createdDtm": null,
    "updatedBy": null,
    "updatedDtm": null,
    "statusIndicator": null,
    "signatoryEmail": "xyz@gmail.com",
    "leaseMlaNo": "OPM2",
    "statusDescription": "APPROVED"
  }]
}

我在Reactjs工作,我希望我的对象被迭代,以便对象的内部数组 mlaList 被迭代以一个接一个地显示值。 每当我尝试将.map函数用于父对象时,我得到的错误是“.map不是函数”,下面是我尝试的迭代失败:

{data.map((data, index) => {data.leaseMlaNo}   {data.signatoryEmail})}

我已经提到了与这个问题非常相似的SO问题,但他们只是谈论使用Object.keys迭代对象

请帮助我理解我做错了什么以及实现这个目标的正确方法

2 个答案:

答案 0 :(得分:3)

方法Array#map是Array类的方法,而不是Object类的方法。但是,mlaList属性是一个数组,您可以迭代它。您应该使用data.mlaList.map()

// if the data is stringified - const data = JSON.parse({ the object });
const data = {"lesseeName":"Padyster-7","lesseeRegNo":"12345","lesseeVatNo":"4456","telFaxNo":"1234567891","billingAddress":{"addressId":null,"addressLine1":"XYz , l1 street","addressLine2":"near xyz bank","postalCode":"60000","countryName":"MY","cityName":"Kuala lumpur","stateProvinceCode":"Kuala lumpur"},"mlaList":[{"mlaNo":92,"lesseeId":108,"executionDate":"27/01/2017","signatoryInfo":"Test","overdueRate":3.44,"nonPaymentDays":2,"consolidationTerm":"Monthly","createdBy":null,"createdDtm":null,"updatedBy":null,"updatedDtm":null,"statusIndicator":null,"signatoryEmail":"tooot@gmail.com","leaseMlaNo":"OPM1","statusDescription":"APPROVED"},{"mlaNo":93,"lesseeId":108,"executionDate":"03/01/2017","signatoryInfo":"tess","overdueRate":5.77,"nonPaymentDays":2,"consolidationTerm":"Bi-Monthly","createdBy":null,"createdDtm":null,"updatedBy":null,"updatedDtm":null,"statusIndicator":null,"signatoryEmail":"xyz@gmail.com","leaseMlaNo":"OPM2","statusDescription":"APPROVED"}]};

const result = data.mlaList.map((o, index) => o.signatoryEmail); // in react <div key={index}>{o.signatoryEmail}</div> for example

console.log(result);

答案 1 :(得分:2)

array.prototype.map是一个数组函数,不适用于对象,因此您需要在mlalist键上调用它:

86400