Untitled
unknown
javascript
a year ago
2.1 kB
4
Indexable
Never
const schemaArr = { "body": [ // ... (your schemaArr data) ] }; const state = { "updateKycStatus": { "value": [ "a0" ] }, "updateTRM": { "value": [ "a15" // Example with an out-of-bounds index ] }, "rejectReason": "" }; const newConvertedState = {}; // Iterate through the keys in the state object for (const key in state) { if (state.hasOwnProperty(key)) { // Find the corresponding schema item in schemaArr const schemaItem = schemaArr.body.find(item => item.id === key); // If no schema item is found for the current key if (!schemaItem) { console.warn(`No id found in schemaArr for the key ${key}`); // Set the value to null in newConvertedState newConvertedState[key] = null; } else { // If the schema item has a "select" type if (schemaItem.type === "select") { // If no "value" associated in the state object if (!state[key].value) { console.warn(`Id is found in schemaArr with "select" type but no "value" associated for the key ${key}`); // Set the value to null in newConvertedState newConvertedState[key] = null; } else { // Extract the index from the state value (e.g., "a0" -> 0) const index = parseInt(state[key].value[0].substr(1)); // Get the keys of the available options in the schemaItem const optionsKeys = Object.keys(schemaItem.options); // If the index is within bounds of the available options if (index >= 0 && index < optionsKeys.length) { const selectedOption = schemaItem.options[optionsKeys[index]]; newConvertedState[key] = selectedOption.id; } else { console.warn(`Index out of bounds for the key ${key}`); // Set the value to null in newConvertedState newConvertedState[key] = null; } } } else { // If the schema item type is not "select", set the value to null newConvertedState[key] = null; } } } } console.log(newConvertedState);