Home > Net >  Clear each value of each key inside an object
Clear each value of each key inside an object

Time:01-10

I don't figure it out, how to clear each value of each key inside an object.

The result should be like this.

const initialObject = { a: "valueA", b: "valueB", c: "valueC" };

const finalObject = { a: "", b: "", c: "" };

I'm using Typescript.

Thank you for your help.

CodePudding user response:

Map the keys to an array of [key, ""] and then convert to an object using Object.fromEntries():

const initialObject = {a: "valueA",  b: "valueB", c: "valueC"}
        
const finalObject = Object.fromEntries(
  Object.keys(initialObject)
    .map(key => [key, ""])
)

console.log(finalObject)

CodePudding user response:

You can iterate through the initialObject keys and for each key create that property in the finalObject with a value of empty strings ""

const initialObject = { a: "valueA", b: "valueB", c: "valueC" };
const finalObject = {};

for (let key in initialObject) {
  finalObject[key]= "";
}

console.log(finalObject);

  •  Tags:  
  • Related