I have one object like
const data = {
"title": "new book"
"IsSale": 1,
"price" : 100,
}
I want to change to
const data = {
"title": "new book"
"IsSale": true,
"price" : 100,
}
"IsSale": 1 > "IsSale": true
If it is array, we can use reduce
method, to change it. But for Object do we have any method.
Of course, we don't convert to array, deduce, and convert back to Object
CodePudding user response:
If it is array, we can use deduce [sic] method, to change it. But for Object do we have any method.
If it were an array, you'd use map
for this, not reduce
(I assume you meant reduce
). Or an explicit loop.
Just to get it out the way: The simple version is to just write an 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 for some reason you needed to do something other than that, there is a way to do something similar with objects, but it involves a lot of intermediary objects. (Often that doesn't matter; sometimes it does.) You could use Object.entries
to get an array of [key, value]
arrays, then use map
on that, then use Object.fromEntries
to convert that back into an object:
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);
Or you might just use a for-in
loop instead:
const updated = {};
for (const key in data) {
if (Object.hasOwn(data, 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 (Object.hasOwn(data, key)) {
const value = data[key];
updated[key] = key === "IsSale" ? !!value : value;
}
}
console.log(updated);
(Note: That uses the newish Object.hasOwn
, apply a polyfill if you have to target obsolete environments that don't have it.)
CodePudding user response:
Seems like you want to convert the value of a property within an Object to boolean (true/false
). Here's a small helper function to do such a conversion. It can be used to add and/or convert the property IsSale
in an array of objects.
// Note: !!data.IsSale can be used as shorthand
const sale2bool = data => data.IsSale = Boolean(data.IsSale);
const data = [{
"title": "new book",
"IsSale": 1,
"price" : 100,
}, {
"title": "another new book",
"IsSale": 0,
"price" : 110,
}, {
"title": "old book",
"IsSale": 15,
"price" : 50,
}, {
// Note: no IsSale property
"title": "old book",
"price" : 50,
}];
data.forEach(sale2bool);
console.log(data);
.as-console-wrapper {
max-height: 100% !important;
}