Skip to content
Advertisement

How to convert array to object and assign value in Javascript?

I have array value and object for data mapping. reduce method is not working for object mapping, here is sample data.

the array value is

let array = [ "payload", "offer", "application_id" ]

object value is

let data = {
                organization_id: 4002400004,
                organization_name: 'Velocity Global Integration Sandbox',
                action: 'offer_updated',
                payload: {
                    offer: {
                        id: 4524843004,
                        application_id: 31948577004,
                        user_id: 4123647004,
                        version: 1,
                        sent_on: null,
                        resolved_at: '2022-05-19T06:21:25.084Z',
                        start_date: '2022-05-17',
                        notes: null,
                        job_id: 4298940004,
                        offer_status: 'Accepted'
                    },
                    "resume": {
                        name: "manikandan"
                    }
                }
            }

need to form new object with the response

let payload = {
    offer: {
        application_id: 343645656
    }
}

Advertisement

Answer

While I usually avoid recommending the usage of eval, this specific case seems to be a valid use-case for eval. You can simply extract the first item of the array as a variable name and extract the subsequent array items as levels:

let array = [ "payload", "offer", "application_id" ]

let data = {
                organization_id: 4002400004,
                organization_name: 'Velocity Global Integration Sandbox',
                action: 'offer_updated',
                payload: {
                    offer: {
                        id: 4524843004,
                        application_id: 31948577004,
                        user_id: 4123647004,
                        version: 1,
                        sent_on: null,
                        resolved_at: '2022-05-19T06:21:25.084Z',
                        start_date: '2022-05-17',
                        notes: null,
                        job_id: 4298940004,
                        offer_status: 'Accepted'
                    },
                    "resume": {
                        name: "manikandan"
                    }
                }
            }

/*let payload = {
    offer: {
        application_id: 343645656
    }
}*/

function getNestedObject(data, array, index) {
    return {[array[index]] : ((index < array.length - 1) ? getNestedObject(data[array[index]], array, index + 1) : data[array[index]])};
}

eval(`var ${array[0]} = getNestedObject(data[array[0]], array, 1)`);
console.log(payload);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement