How can I parse the true
and false
strings in an array to become boolean in Javascript?
For instance,
from:
{"id":1,"dashboardId":1,"w":2,"h":2,"x":0,"y":0,"i":"n0","minW":1,"minH":1,"maxH":1000,"moved":"false","static":"false","widget":"Photo"}
to:
{"id":1,"dashboardId":1,"w":2,"h":2,"x":0,"y":0,"i":"n0","minW":1,"minH":1,"maxH":1000,"moved":false,"static":false,"widget":"Photo"}
The values from moved
and static
have to be a boolean but they appear as a string. Is there a way to only change those values?
This is the function where I fetch the arrays:
loadData = () => {
let dashboardId = 1;
return axios
.get('api/dashboards/' + dashboardId)
.then(result => {
//@TODO Parse true and false strings to become booleans
console.log(result);
this.setState({
items: result.data,
selectedOption: '',
newCounter: originalLayouts.length
});
})
.catch(error => {
console.log(JSON.stringify(this.state.items));
console.error('error: ', error);
})
};
parse the true and false strings in an array to become boolean
Strings in an array, you say? Iterate using Array.map()
const items = ["true", "false", "something else"]
const booleans = items.map(boolFromStringOtherwiseNull)
console.log({items, booleans}) // show result
function boolFromStringOtherwiseNull(s) {
if (s == 'true') return true
if (s == 'false') return false
return null
}
Objects? Iterate using Object.values()
const data = {"id":1,"dashboardId":1,"w":2,"h":2,"x":0,"y":0,"i":"n0","minW":1,"minH":1,"maxH":1000,"moved":"false","static":"false","widget":"Photo"};
const booleans = Object.values(data).map(boolFromStringOtherwiseNull); // convert
console.log({data, booleans}); // show result
function boolFromStringOtherwiseNull(s) {
if (s == 'true') return true
if (s == 'false') return false
return null
}
Convert only boolean strings, and maintain the original Object's structure?
const data = {"id":1,"dashboardId":1,"w":2,"h":2,"x":0,"y":0,"i":"n0","minW":1,"minH":1,"maxH":1000,"moved":"false","static":"false","widget":"Photo"}
const result = Object.entries(data)
.map(boolFromStringOtherwiseNoOp) // convert 'boolean strings' to boolean
.reduce(gatherObjectFromEntries, {}) // collect all entries into 1 object
console.log({data, result}); // result is an object where non-boolean-strings are untouched.
function boolFromStringOtherwiseNoOp([key, value]) {
if (value == 'true') return [key, true]
if (value == 'false') return [key, false]
return [key, value]
}
function gatherObjectFromEntries(accumulation, [key, value]) {
accumulation[key] = value
return accumulation
}
Hope this helps. Cheers,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With