[英]TS/JS - Get "value" from an Array of Objects if a Property of an Object from the Array matches another Property from a separate Object
THE PROBLEM:问题:
I have an array of Objects.我有一个对象数组。 And a currentObject, that I currently am viewing.
还有一个 currentObject,我目前正在查看。 I want to get the value from a Property that comes from the Array of Objects, if 2 other properties match.
如果 2 个其他属性匹配,我想从来自对象数组的属性中获取值。
Here is the Array, simplified:这是简化的数组:
ARRAY = [{
id: 1,
metadata: {author: "Company1"}
},
{
id: 2,
metadata: {author: "Company2"}
}
Here is the Object, simplified:这是简化的对象:
OBJECT = {
name: "Something
templateId: 2
}
So, basically, I want to return, the metdata.author
information, if the ARRAY.id
, matches the OBJECT.templateId
..所以,基本上,我想返回,
metdata.author
信息,如果ARRAY.id
匹配OBJECT.templateId
..
Here is the code I wrote..这是我写的代码..
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
Any ideas, on how to make this work?关于如何使这项工作有任何想法? I tried to
filter
as well, with the same condition, but that returned undefined
, when I called it in my ReactComponent.我也尝试使用相同的条件进行
filter
,但是当我在 ReactComponent 中调用它时返回了undefined
。
is this what you need?这是你需要的吗?
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))
You are on the right path:您走在正确的道路上:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.