I want to change an object key with another, depending by condition.
const obj = {
name: 'carl',
age: 2
};
const filterF = (obj, toChange, newV) => {
return Object.keys(obj).reduce((acc, key) => {
if (obj[key] === toChange) {
acc[key] = newV;
}
return acc
}, {})
}
console.log(filterF(obj, 'name', 'newName'))
Basically i expect this:
{
name: 'newName',
age: 2
};
Running my code i get an empty object. How to fix the code?
You only need to add or update the value
const obj = {
name: 'carl',
age: 2
};
const addOrUpdate= (obj, key, value) => {
// no need to itterate
obj[key] = value;
return obj
}
console.log(addOrUpdate(obj, 'name', 'newName'))
If you only need to update the value if its key already exists in object.
const obj = {
name: 'carl',
age: 2
};
const update= (obj, key, value) => {
// no need to itterate
if(obj.hasOwnProperty(key)) {
obj[key] = value;
}
return obj
}
console.log(update(obj, 'name', 'newName'))
// no new value added
console.log(update(obj, 'city', 'my city'))
If you just want to know how to achieve this with reduce for leaning purpose only.
you should not use reduce here since you are just creating a shallow copy of the previous object, but just for learning purpose i have added an example and where you went wrong.
const obj = {
name: 'carl',
age: 2
};
const filterF = (obj, toChange, newV) => {
return Object.keys(obj).reduce((acc, key) => {
// you had key wronly written as keys, and comparing objectp[key] value with new key
if (key === toChange) {
acc[key] = newV;
} else {
acc[key] = obj[key];
}
return acc
}, {})
}
console.log(filterF(obj, 'name', 'newName'))
You should apply the changes by assigning a config to the original object.
This will allow you to change many properties at once.
const
obj = { name: 'carl', age: 2 },
alter = (obj, config) => Object.assign(obj, config); // or { ...obj, ...config }
console.log(alter(obj, { name: 'newName' }))
If you really want to split-out the key and value as separate params, you could try this instead:
const
obj = { name: 'carl', age: 2 },
alter = (obj, key, value) => Object.assign(obj, { [key]: value });
console.log(alter(obj, 'name', 'newName'))