0

I have the following JSON:

[{"active":false,"id":1,"name":"Day"},{"active":true,"id":2,"name":"Evening"},{"active":false,"id":3,"name":"Night"},{"active":false,"id":4,"name":"Away"}]

I'm trying to write JavaScript to find the "name" that is "active" set as "true".

function updateMode() {

var responseString = '';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        responseString = xhttp.responseText;

        var obj = JSON.parse(responseString);

        obj.forEach(function(key, index){

        console.log(key.active);
        console.log(key.name);
        alert(index + "." + key.active + "," + key.name);

        if (key.active == "true") {
            alert("mode is true");
        }

        });

    }

};

xhttp.open("GET", "http://192.168.0.xxx/blahblahblah", true);
xhttp.send();

};

The if (key.active == "true") is not working. How to return the "name" that has "active" true?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Scotsman
  • 177
  • 1
  • 9
  • 3
    `true` isn't the same as `"true"`. Simply use `if (key.active)` –  May 20 '20 at 17:48
  • 1
    If you want to find the element in the array where a property is equal to a constant, use [`find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find). This really has nothing to do with JSON. Once you passed it through `JSON.parse` it's no longer JSON. – Heretic Monkey May 20 '20 at 17:51
  • 1
    Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Heretic Monkey May 20 '20 at 17:52

2 Answers2

0

Basically you can achieve this as,

  if(key.active) alert(key.name);

I m adding one example for this, hope this will help you out!

const array = [
 {"active":false,"id":1,"name":"Day"},           
 {"active":true,"id":2,"name":"Evening"},
 {"active":false,"id":3,"name":"Night"},
 {"active":false,"id":4,"name":"Away"}
];

array.forEach((value) => {
  if(value.active) alert(`selected value is ${value.name}`);
});
Ayesha Malik
  • 26
  • 1
  • 5
0

If we are not sure about datatype, then we should always make sure to check correct type in the if condition. If don't we will have situation like yours,

   key.active == true //false for string value i.e "true"
//or 
   key.active == true" //string, false for boolean value i,e true

Thus either we should check both condition or better, use:

    key.active.toString() == "true" // returns true for both boolean as well as string
Rishu Ranjan
  • 494
  • 4
  • 7