【问题标题】:TS/JS - Get "value" from an Array of Objects if a Property of an Object from the Array matches another Property from a separate ObjectTS/JS - 如果数组中对象的属性与单独对象中的另一个属性匹配,则从对象数组中获取“值”
【发布时间】:2020-04-09 19:14:04
【问题描述】:

问题:

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

这里是简化的数组:

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

这是简化的对象:

OBJECT = {
 name: "Something
 templateId: 2
}

所以,基本上,我想返回 metdata.author 信息,如果 ARRAY.id 匹配 OBJECT.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。

【问题讨论】:

  • 假设您的return 来自您的getAuthorInfo,您将从您的ARRAY 获得一个对象。然后使用.metadata.author获取作者
  • 返回对象。不是数组中的对象。所以,信息不存在。
  • 您正在 connTemplates 上运行 .find(),这是您的阵列。您只能从您的数组中获取undefined 或一个对象作为回报,我看不出您是如何获得OBJECT 作为回报的?

标签: javascript arrays typescript filter find


【解决方案1】:

这是你需要的吗?

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))

【讨论】:

  • 返回对象。不是数组中的对象。所以信息不存在..
【解决方案2】:

你在正确的道路上:

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);

【讨论】:

  • 我认为他想深入研究对象并获得实际作者......
  • 我想我错了...根据对我的回答的回答...我不确定我是否理解这个问题...
猜你喜欢
  • 2022-11-21
  • 2022-09-23
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 2019-07-14
相关资源
最近更新 更多