Home > Enterprise >  Search for value contained in array of objects in property of object contained in array
Search for value contained in array of objects in property of object contained in array

Time:02-11

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

CodePudding user response:

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
}

CodePudding user response:

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

  • Related