Olivier.C
Olivier.C

Reputation: 181

Clear each value of each key inside an object

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.

Upvotes: 1

Views: 83

Answers (2)

Ran Turner
Ran Turner

Reputation: 18116

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

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 192527

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)

Upvotes: 1

Related Questions