Reputation: 261
var object = {
'ex1': '123',
'ex2': '234',
'ex3': '345',
'ex4': '456',
'ex5': '678'
}
What is the best way to remove values without remove property as follows?
var object = {
'ex1': '',
'ex2': '',
'ex3': '',
'ex4': '',
'ex5': ''
}
Upvotes: 3
Views: 119
Reputation: 1
I think there are all many approaches.
I like this one:
const obj = {
ex1: '123',
ex2: '234',
ex3: '345',
ex4: '456',
ex5: '678'
}
for (const p in obj) obj[p] = null;
console.log(obj);
But I find also acceptable the one using ES6 iterators:
const obj1 = {
ex1: '123',
ex2: '234',
ex3: '345',
ex4: '456',
ex5: '678'
}
for (k of Object.getOwnPropertyNames(obj1)) {
obj1[k] = null;
}
console.log(obj1);
Upvotes: 0
Reputation: 56843
Simply use for...in
to iterate over the object properties:
var object = {
'ex1': '123',
'ex2': '234',
'ex3': '345',
'ex4': '456',
'ex5': '678'
}
for (const prop in object) { object[prop] = '' };
console.log(object);
Upvotes: 3
Reputation: 10669
Also, you can reach it by using the reduce function.
var obj = {
'ex1': '123',
'ex2': '234',
'ex3': '345',
'ex4': '456',
'ex5': '678'
}
const new_object = Object.keys(obj).reduce((agg, item) => {
agg[item] = ''
return agg
}, {})
console.log(new_object)
The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.
EDIT:
Notice that reduce will return an new object (It will not override the existing object).
If you prefer to override the existing object, look at other answers who use the forEach
loop.
Upvotes: 0
Reputation: 282130
Iterate though the object keys using Object.keys
and set the values to empty. Also you need to name you object something other than Object
since its already a predefined object in javascript.
var object = {
'ex1': '123',
'ex2': '234',
'ex3': '345',
'ex4': '456',
'ex5': '678'
}
Object.keys(object).forEach(key => {
object[key] = ''
})
console.log(object);
Upvotes: 2
Reputation: 386868
You could get the keys, iterate and assign a wanted value to the properties.
var object = { ex1: '123', ex2: '234', ex3: '345', ex4: '456', ex5: '678' };
Object
.keys(object)
.forEach(k => object[k] = '');
console.log(object);
Upvotes: 3