0

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;
      }
    }
  };
Rodrigo
  • 3
  • 2
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find – malarres Feb 10 '22 at 16:01
  • Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – S1LV3R Feb 10 '22 at 16:16

2 Answers2

1

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
}
minikdev
  • 91
  • 5
0

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

S1LV3R
  • 146
  • 3
  • 15