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
JavaScript
x
2
1
let array = [ "payload", "offer", "application_id" ]
2
object value is
JavaScript
1
23
23
1
let data = {
2
organization_id: 4002400004,
3
organization_name: 'Velocity Global Integration Sandbox',
4
action: 'offer_updated',
5
payload: {
6
offer: {
7
id: 4524843004,
8
application_id: 31948577004,
9
user_id: 4123647004,
10
version: 1,
11
sent_on: null,
12
resolved_at: '2022-05-19T06:21:25.084Z',
13
start_date: '2022-05-17',
14
notes: null,
15
job_id: 4298940004,
16
offer_status: 'Accepted'
17
},
18
"resume": {
19
name: "manikandan"
20
}
21
}
22
}
23
need to form new object with the response
JavaScript
1
6
1
let payload = {
2
offer: {
3
application_id: 343645656
4
}
5
}
6
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:
JavaScript
1
37
37
1
let array = [ "payload", "offer", "application_id" ]
2
3
let data = {
4
organization_id: 4002400004,
5
organization_name: 'Velocity Global Integration Sandbox',
6
action: 'offer_updated',
7
payload: {
8
offer: {
9
id: 4524843004,
10
application_id: 31948577004,
11
user_id: 4123647004,
12
version: 1,
13
sent_on: null,
14
resolved_at: '2022-05-19T06:21:25.084Z',
15
start_date: '2022-05-17',
16
notes: null,
17
job_id: 4298940004,
18
offer_status: 'Accepted'
19
},
20
"resume": {
21
name: "manikandan"
22
}
23
}
24
}
25
26
/*let payload = {
27
offer: {
28
application_id: 343645656
29
}
30
}*/
31
32
function getNestedObject(data, array, index) {
33
return {[array[index]] : ((index < array.length - 1) ? getNestedObject(data[array[index]], array, index + 1) : data[array[index]])};
34
}
35
36
eval(`var ${array[0]} = getNestedObject(data[array[0]], array, 1)`);
37
console.log(payload);