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
}
}
CodePudding user response:
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);
CodePudding user response:
Here's a relatively simple solution using loops.
The idea is to iterate over the array, and always keep a reference to the current object. Since objects are references, modifying o
will modify the object nested in ret
.
function pair(array, data) {
const ret = {};
let o = ret, d = data;
for (let i = 0; i < array.length - 1; i ) {
const k = array[i];
o[k] = {};
o = o[k];
d = d[k];
}
const k = array[array.length - 1];
o[k] = d[k];
return ret;
}