简体   繁体   中英

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. I want to get the value from a Property that comes from the Array of Objects, if 2 other properties match.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM