React:迭代对象列表来过滤或映射Object

时间:2018-04-09 20:30:48

标签: javascript jquery reactjs react-native

我有CutomerType对象和Customer对象的列表。 Customer对象上有cutomerType id属性。根据客户对象上的客户类型ID,我必须循环或映射正确的customerType对象并取消显示名称代码。



[ {
  "id" : "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
  "code" : "0",
  "name" : "UN"
}, {
  "id" : "674b76b8-f1ac-5c14-e053-ce5e1cac867d",
  "code" : "1",
  "name" : "NON-UN"
}, {
  "id" : "674b76b8-f1ad-5c14-e053-ce5e1cac867d",
  "code" : "2",
  "name" : "COS-UN"
}, {
  "id" : "674b76b8-f1ae-5c14-e053-ce5e1cac867d",
  "code" : "NA",
  "name" : NA"
} ]


Customer
{
  "id" : "1",
   "name": "Jhon",
   "type": "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",   
}




3 个答案:

答案 0 :(得分:1)

希望这很清楚,如果不随意问

const loop = // whole array;
const customer = // customer object
loop.find(el => el.id === customer.type).name

答案 1 :(得分:1)

这就是你能做的。

const customerCodeArray = [{
  "id": "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
  "code": "0",
  "name": "UN"
}, {
  "id": "674b76b8-f1ac-5c14-e053-ce5e1cac867d",
  "code": "1",
  "name": "NON-UN"
}, {
  "id": "674b76b8-f1ad-5c14-e053-ce5e1cac867d",
  "code": "2",
  "name": "COS-UN"
}, {
  "id": "674b76b8-f1ae-5c14-e053-ce5e1cac867d",
  "code": "NA",
  "name": "NA"
}]


const customer = {
  "id": "1",
  "name": "Jhon",
  "type": "5436d5fd-e3ea-4e09-be4a-a80967cd72e5",
};

const getCustomerCode = (type) => {
  const filterList = customerCodeArray.filter((obj) => obj.id === type);
  if (filterList.length > 0) {
    return filterList[0];
  }
}
console.log(getCustomerCode(customer.type));

答案 2 :(得分:0)

const filteredResult = customerCodeArray.filter(type => type.id === Customer.type);

console.log(filteredResult[0].name);