How to parse true and false strings in an array to become booleans

Viewed 4758

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);
            })
};
5 Answers

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,

You can iterate the object, and check its value strictly for "false" or "true" and parse them manually to boolean.

E.g.

function mapObjectValues (obj = {}) {
    for (var key in obj) {
      var val = obj[ key ];
      
      if (val === "false") {
          obj[ key ] = false;
      }
      else if (val === "true") {
          obj[ key ] = true;
      }
    }
}

var tmp = {
  "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"
};

mapObjectValues(tmp);

console.log(tmp);

You can loop over the object keys and then compare those boolean strings and assign the actual Boolean value to that property:

var 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"};
Object.keys(data).forEach((key) => {
  if(data[key] === 'false'){
    data[key] = false;
  }
  if(data[key] === 'true'){
    data[key] = true;
  }
});
console.log(data);

You can do like this:

var 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" };
Object.keys(data).forEach((key) => {
    if (data[key] === 'false' || data[key] === 'true') {
        data[key] = JSON.parse(data[key]);
    }
});
console.log(data);

`

for(key in a){

   a[key] == "true" ? a[key] = true : a[key] == "false" ?  a[key] = false : ''; 

}

You can simply loop over the object and use the ternary operator, to make it concise, where a is your original object

Related