TS / JS-如果对象数组的属性与另一个对象的另一个属性相匹配,则从对象数组获取“值”

时间:2019-12-17 09:54:49

标签: javascript arrays typescript filter find

问题:

我有一个对象数组。还有我当前正在查看的currentObject。如果其他两个属性匹配,我想从对象数组的属性中获取值。

这是简化的数组:

ARRAY = [{
  id: 1,
  metadata: {author: "Company1"}
 },
 {
  id: 2,
  metadata: {author: "Company2"}
 }

这里是对象,简化了:

OBJECT = {
 name: "Something
 templateId: 2
}

因此,基本上,我想返回metdata.author信息,如果ARRAY.idOBJECT.templateId相匹配。。

这是我写的代码。

const getAuthorInfo = (connTemplates: ARRAY[], currentConn: ITEM_OBJECT) => {
  connTemplates.find((connTemplate: ARRAY_ITEM_OBJECT) => connTemplate.id === currentConn.templateId);
};

console.log('Author Info:', connection); // This though returns the OBJECT, not the ARRAY_ITEM

关于如何进行这项工作的任何想法?我也尝试在相同条件下filter,但是当我在ReactComponent中调用它时返回了undefined

2 个答案:

答案 0 :(得分:0)

这是您需要的吗?

const arr = [{
  id: 1,
  metadata: { author: "Company1" }
},
{
  id: 2,
  metadata: { author: "Company2" }
}]

const obj = {
  name: "Something",
  templateId: 2
}



function getAuthorInfo(arr, obj) {
  const arrItem = arr.find(item => item.id === obj.templateId)
  return arrItem.metadata.author
}

console.log(getAuthorInfo(arr, obj))

答案 1 :(得分:0)

您在正确的道路上:

const result = arr.find(f => f.id == obj.templateId).metadata.author;

    const arr = [{
      id: 1,
      metadata: {author: "Company1"}
     },
     {
      id: 2,
      metadata: {author: "Company2"}
     }]
    
     const obj = {
      name: "Something",
      templateId: 2
     }
    
    
    const result = arr.find(f => f.id == obj.templateId);
    
    console.log(result);

相关问题