Home > OS >  How to return inner matched object from nested Array.prototype.find() in JavaScript?
How to return inner matched object from nested Array.prototype.find() in JavaScript?

Time:10-14

The function below prints the modified subdata object with the parent id. How to return the inner object from the getSubdataObj function instead of printing it? Please Note: id & programId are unique

const data = [
     {
         id:1,
         subdata: [
             {
                 programId: 11,
                 programName: 'ABC'
             },
             {
                 programId: 12,
                 programName: 'DEF'
             }
        ]
     },
     {
         id:2,
         subdata: [
             {
                 programId: 21,
                 ProgramName: 'PQR'
             },
             {
                 programId: 22,
                 programName: 'XYZ'
             }
        ]
     }
]

function getSubdataObj(programId){
    data.find(datum => {
        datum.subdata.find(subdata => {
           if(programId == subdata.programId){
               subdata["id"] = datum.id // Add parent id inside matched obj
               console.log(subdata)
           }
        })
    })
}

getSubdataObj(11) // { programId: 11, programName: 'ABC', id: 1 }

if I add return statement, it returns the whole parent object. I only want inner child matched object.

function getSubdataObj(programId){
    return data.find(datum => {
        return datum.subdata.find(subdata => {
           if(programId == subdata.programId){
               subdata["id"] = datum.id // Add parent id inside matched obj
               return subdata
           }
        })
    })
}

// Current return value:
{ id: 1,
  subdata: [ 
     { programId: 11, programName: 'ABC', id: 1 },
     { programId: 12, programName: 'DEF' } 
   ] 
}

// Expected return value:
{ programId: 11, programName: 'ABC', id: 1 }

CodePudding user response:

Should return from the inner find and from the function itself.

function getSubdataObj(programId) {
    let result = null;

    for (const datum of data) {
        result = datum.subdata.find(subdata => {
            if (programId == subdata.programId) {
                subdata["id"] = datum.id;
                return subdata;
            }
        });

        if (result)
            break;
    }

    return result;
}

console.log(getSubdataObj(11))

Example output:

{ programId: 11, programName: 'ABC', id: 1 }

CodePudding user response:

const getSubDataObj = (programId) => data.
    flatMap(datum => datum.subdata.map(child => ({...child, id: datum.id}))).
    find(child => child.programId === programId)
  • Related