Home > Back-end >  Trying to access the name of the object
Trying to access the name of the object

Time:06-28

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

}

CodePudding user response:

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));

CodePudding user response:

you can do something like this

const dataToInsert = {
  FOI_OMG_101: {
    name: "jghj.pdf",
    value: "base64"
  }
};

const output = Object.entries(dataToInsert).reduce((res, [key, {name, value}]) => ({
    field: key.split('_').pop(),
    fileName: name,
    value
}), {}) 

console.log(output)

  • Related