I want to create expectedObj from currentObj to be sent as response to the API. How can I do it?
The "value" and "label" will always have same values.
These are fixed set of keys. ignore_whitespace is not needed in expectedObj. No other keys are required to be removed.
let currentObj = {
"partnerId": "1",
"platform": {
"label": "ADP",
"value": "ADP"
},
"subPlatform": {
"value": "Health",
"label": "Health"
},
"activeIndicator": {
"value": "Inactive",
"label": "Inactive"
},
"partnerNotes": "",
"ignore_whitespace": false
}
let expectedObj={
"partnerId": "1",
"platform": "ADP",
"subPlatform": Health,
"activeIndicator": "Inactive",
"partnerNotes": ""
}
What I have tried is this
for let (item in currentObj) {
something
}
Something like this should do what you're looking for:
const expectedObj = Object.entries(currentObj).reduce((a, [k, v]) => {
if (v?.value !== undefined) a[k] = v.value;
else a[k] = v;
return a;
}, {});
Expand this code snippet for a working example:
const currentObj = {
partnerId: '1',
platform: {
label: 'ADP',
value: 'ADP',
},
subPlatform: {
value: 'Health',
label: 'Health',
},
activeIndicator: {
value: 'Inactive',
label: 'Inactive',
},
partnerNotes: '',
ignore_whitespace: false,
};
const expectedObj = Object.entries(currentObj).reduce((a, [k, v]) => {
if (v?.value !== undefined) a[k] = v.value;
else a[k] = v;
return a;
}, {});
console.log(expectedObj);
This will do the transforms you need (as discussed in the comments, no more keys are expected, values are always the same as labels, etc):
let currentObj = {
"partnerId": "1",
"platform": {
"label": "ADP",
"value": "ADP"
},
"subPlatform": {
"value": "Health",
"label": "Health"
},
"activeIndicator": {
"value": "Inactive",
"label": "Inactive"
},
"partnerNotes": "",
"ignore_whitespace": false
}
let expected = {
...currentObj,
platform: currentObj.platform.value,
subPlatform: currentObj.subPlatform.value,
activeIndicator: currentObj.activeIndicator.value,
}
delete expected.ignore_whitespace;
console.log(expected);