0

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...

str
  • 42,689
  • 17
  • 109
  • 127
James
  • 1,190
  • 5
  • 27
  • 52
  • Please read [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str May 31 '18 at 13:27
  • If you are using angular, shouldn't you be using Typescript instead of Javascript ? – Seblor May 31 '18 at 13:27
  • Possible duplicate of [How can I convert a string to boolean in JavaScript?](https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript) – Protozoid May 31 '18 at 13:30
  • Would it not be better to tackle the problem at the server API and have it return valid JSON for boolean values like `"{...,"isSingle":true}"`? – HMR May 31 '18 at 14:15

3 Answers3

4

Simple loop through the objects to convert string to bool:

yourArray.forEach(x => x.isSingle = x.isSingle === 'true');
jbrown
  • 3,025
  • 1
  • 15
  • 22
1

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
});
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
0

Using reduce method.

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