If the data is in an array, you can use the map method to make changes. But when dealing with an Object, are there any similar methods available?
If the data were actually an array, you would utilize the map
function rather than reduce
(assuming you meant reduce
). Alternatively, you could use a standard loop.
To keep it simple, you can update an object by creating a new object literal:
const updated = {
...data,
IsSale: !!data.IsSale
};
const data = {
"title": "new book",
"IsSale": 1,
"price" : 100,
};
const updated = {
...data,
IsSale: !!data.IsSale
};
console.log(updated);
If you need to do something more complex, you can achieve a similar result with objects using a series of intermediary steps involving arrays. This may include using Object.entries
, map
, and Object.fromEntries
:
const updated = Object.fromEntries(
Object.entries(data).map(([key, value]) =>
[key, key === "IsSale" ? !!value : value]
)
);
const data = {
"title": "new book",
"IsSale": 1,
"price" : 100,
};
const updated = Object.fromEntries(
Object.entries(data).map(([key, value]) =>
[key, key === "IsSale" ? !!value : value]
)
);
console.log(updated);
Alternatively, you can use a for-in
loop as another approach:
const updated = {};
for (const key in data) {
if (data.hasOwnProperty(key)) {
const value = data[key];
updated[key] = key === "IsSale" ? !!value : value;
}
}
const data = {
"title": "new book",
"IsSale": 1,
"price" : 100,
};
const updated = {};
for (const key in data) {
if (data.hasOwnProperty(key)) {
const value = data[key];
updated[key] = key === "IsSale" ? !!value : value;
}
}
console.log(updated);
(Please note that the example above uses the modern Object.hasOwn
; consider applying a polyfill for outdated environments that lack support for it.)