根据另一个对象的键值获取键值

时间:2020-06-12 07:05:54

标签: javascript arrays object

我有这个对象数组

 [{chainTypeCode: "DIRECT", chainTypeId: "1"},
  {chainTypeCode: "MAGT", chainTypeId: "2"},
  {chainTypeCode: "MAGT_AGT", chainTypeId: "3"},
  {chainTypeCode: "MAGT_AGT_SAGT", chainTypeId: "4"}]

我想创建一个函数getChainTypeCode(chainTypeId),其中如果我传递一个chainTypeId,它将返回一个chainTypeCode

2 个答案:

答案 0 :(得分:0)

您可以使用find()

getCode = (arr, id)=> arr.find(p=>p.chainTypeId == id).chainTypeCode

答案 1 :(得分:0)

您可以使用find

function getChainTypeCode(chainTypeId, chainTypeList) {
    return chainTypeList.find(chainType => chainType.chainTypeId == chainTypeId).chainTypeCode;
}

var obj = [{chainTypeCode: "DIRECT", chainTypeId: "1"},
  {chainTypeCode: "MAGT", chainTypeId: "2"},
  {chainTypeCode: "MAGT_AGT", chainTypeId: "3"},
  {chainTypeCode: "MAGT_AGT_SAGT", chainTypeId: "4"}];

var result = getChainTypeCode(1, obj);
console.log(result);
相关问题