I am trying to access the name of the object (FOI_OMG_101) and extract 101 from the name and display it in output.field
const dataToInsert = {
FOI_OMG_101 : {
name : "jghj.pdf",
value: "base64"
}
};
const output = {
field: dataToInsert.substring(8),
fileName: dataToInsert.FOI_OMG_101.name,
value: dataToInsert.FOI_OMG_101.value
}
>Solution :
You can create a function that accepts a source object and a key and returns the desired target object.
For extracting the number out of the key, you can split the key by _ and then grab the last item using at.
function generateOutput(source, key) {
const desiredKey = Object.keys(source).find((k) => k === key);
if (!desiredKey) {
return null;
}
return {
field: desiredKey.split("_").at(-1),
fileName: source[key].name,
value: source[key].value,
};
}
const
dataToInsert = { FOI_OMG_101: { name: "jghj.pdf", value: "base64" } },
key = "FOI_OMG_101";
console.log(generateOutput(dataToInsert, key));