Rodrigo
Rodrigo

Reputation: 13

Search for value contained in array of objects in property of object contained in array

can someone help me with this? I need a function that given a fieldID, searchs within objects and returns the objectID that fieldID is in.

  const objects = [
    {
      objectID: 11,
      fields: [
        { id: 12, name: 'Source ID' },
        { id: 12, name: 'Source ID' },
      ],
    },
    {objectID: 14,
      fields: [
        { id: 15, name: 'Creator' },
      ],},
    {objectID: 16,
      fields: [
        { id: 17, name: 'Type' },
        { id: 18, name: 'Name' },
        { id: 19, name: 'Description' },
      ],},
  ];

SOLVED: Got it working like this:

 const getObjectID = fieldId => {
    for (const object of objects) {
      if (object.fields.find(field => field.id === fieldId)) {
        return object.objectID;
      }
    }
  };

Upvotes: 0

Views: 42

Answers (2)

S1LV3R
S1LV3R

Reputation: 135

Using the find array method:

const objects = [
  { objectId: 1, fields: ["aaa"] },
  { objectId: 2, fields: ["bbb"] },
  { objectId: 3, fields: ["ccc"] },
];

const getObjectId = (id) => objects.find(object.objectId === id);

console.log(getObjectId(2));
// { objectId: 2, fields: ["bbb"] }

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Upvotes: 0

minikdev
minikdev

Reputation: 101

This will work:

const getObjectId = (fieldID) => {
const object = objects.find(object => object.fields.find(field => field.id === fieldID )!== undefined)
if(object) return object.objectID;
return null
}

Upvotes: 1

Related Questions