简体   繁体   中英

Angular js convert string property to boolean inside json object

i'm working with angular js and i have the following array that contains many json object , each objects has the property "isSingle" which contains "true" or "false" , my issue is how to convert this property to boolean true or false :

[
    {
      "noFolder": "AW343",
      "type": "T7",
      "creationDate": "22/05/2017",
      "isSingle": "true"
    },
    {
      "noFolder": "AW35",
      "type": "T34",
      "creationDate": "09/05/2017",
      "isSingle": "false"
    },
    {
      "noFolder": "ASW3",
      "type": "T3",
      "creationDate": "05/07/2017",
      "isSingle": "true"
    },
    {
      "noFolder": "BG5",
      "type": "T1",
      "creationDate": "22/12/2018",
      "isSingle": "false"
    }

]

my desired result is to have objects like :

  {
      "noFolder": "ASW3",
      "type": "T3",
      "creationDate": "05/07/2017",
      "isSingle": true
    }

do you have any idea about how to change the type of the property isSingle to bbolean. i'm using angularjs...

通过对象的简单循环将字符串转换为bool:

yourArray.forEach(x => x.isSingle = x.isSingle === 'true');

Just Iterate over the array and replace the value as per your requirement like this -

var obj = [
    {
      "noFolder": "AW343",
      "type": "T7",
      "creationDate": "22/05/2017",
      "isSingle": "true"
    },
    {
      "noFolder": "AW35",
      "type": "T34",
      "creationDate": "09/05/2017",
      "isSingle": "false"
    },
    {
      "noFolder": "ASW3",
      "type": "T3",
      "creationDate": "05/07/2017",
      "isSingle": "true"
    },
    {
      "noFolder": "BG5",
      "type": "T1",
      "creationDate": "22/12/2018",
      "isSingle": "false"
    }

]

obj.map((e) => {
    e.isSingle == "true" ? e.isSingle = true : e.isSingle = false
});

Using reduce method.

let updated_array = array.reduce(function(acc, elem) {
    acc.push(Object.assign({}, elem, { isSingle: (elem['isSingle'] == true ? true : false) }));
    return acc;
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM