JS —How to reset all values in a Javascript object

Rudashi
1 min readNov 18, 2020

--

Photo by Jose Antonio Gallego Vázquez on Unsplash

There are many ways to “reset” an object’s value in JavaScript. In this article, I will show you my approach to this case.

1. Default Object (not elegant)

let item = {
discount : true,
percentage : false,
qty : true,
unit_price : false,
estimated_cost : true,
description_cost: false,
};
let defaultItem = {
discount : false,
percentage : false,
qty : false,
unit_price : false,
estimated_cost : false,
description_cost: false,
};
item = {...defaultItem}

2. Loop Object (more elegant)

let item = {
discount : true,
percentage : false,
qty : true,
unit_price : false,
estimated_cost : true,
description_cost: false,
};
item = Object.keys(item).reduce((acc, curr) => ({...acc, [curr]: false}), {});

Extra: Loop Object with type check

Object.keys(fields).reduce((acc, curr) => {
if (fields[curr] === null) return { ...acc, [curr]: null };
if (typeof fields[curr] === 'undefined') return { ...acc, [curr]: undefined };
if (typeof fields[curr] === 'boolean') return { ...acc, [curr]: false };
if (typeof fields[curr] === 'string') return {...acc, [curr]: ''};
if (typeof fields[curr] === 'number') return {...acc, [curr]: 0};
if (fields[curr] instanceof Array) return { ...acc, [curr]: [] };
if (typeof fields[curr] === 'object') return { ...acc, [curr]: {} };
}, {})

--

--