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;
      }
    }
  };
2

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks, but what I needed to find the value within the array in fields

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.