Home > Back-end >  object map with the name
object map with the name

Time:06-28

I have an object (obj), I need to map or loop through the dataToInsert object and display the result as shown in the data object. The complexity is that I need to display part of the name of the object in the field value (FOI_OMG_101 to 101)

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

const data=
   {
     field: "101",
     fileName: "jghj.pdf",
     value:"base64"
   }

this is what I have now

for (const [key, value] of 
Object.entries(dataToInsert.FOI_OMG_101)) {
console.log(`${key}: ${value}`);
}

CodePudding user response:

const dataToInsert = {
  FOI_OMG_101 : {
    name : "jghj.pdf",
    value: "base64"
  }
};
const data = {
  field: "101",
  fileName: "jghj.pdf",
  value:"base64"
};
//  Look at the entries of the full object,
//  so you do not have to know the FOI_OMG_101 field name beforehand.
for ([ field, file ] of Object.entries( dataToInsert )) {
  console.log( field );  //  FOI_OMG_101
  console.log( JSON.stringify( file ));  // {"name":"jghj.pdf","value":"base64"}
  const output = {
    field: field,
    fileName: file.name,
    value: file.value
  };
  console.log( JSON.stringify( output ));  // {"field":"FOI_OMG_101","fileName":"jghj.pdf","value":"base64"}
}

You can add additional string manipulation if you have to parse the number 101 out of the string FOI_OMG_101.

CodePudding user response:

You need to split the key on those objects in the loop, and take the value from the last index of this split key as:

export default function App() {
  const dataToInsert = {
    FOI_OMG_101: {
      name: "jghj.pdf",
      value: "base64"
    },
    FOI_OMG_102: {
      name: "abc.pdf",
      value: "base64"
    }
  };

  const [arrData, setArrData] = useState([]);

  useEffect(() => {
    let newArr = [];
    Object.keys(dataToInsert).map((keyName, index) => {
      const fieldNameArr = keyName.split("_");
      newArr = [
        ...newArr,
        {
          field: fieldNameArr.at(-1),
          fileName: dataToInsert[keyName].name,
          value: dataToInsert[keyName].value
        }
      ];
    });
    setArrData(newArr);
  }, []);

  useEffect(() => {
    console.log("arrData", arrData);
  }, [arrData]);

  return (
    <div className="App">
      {arrData.map((item, index) => {
        return <li key={index}>{JSON.stringify(item)}</li>;
      })}
    </div>
  );
}

This is just an example of splitting, you can handle it as you wish. Here, is the sandbox link.

  • Related