jangoertzen
jangoertzen

Reputation: 29

How to return a boolean if any values are false in an array

I'm new to React (and Javascript) and am setting up a very simple dashboard. One component reads a JSON file (MD.json) that looks like this (shortened):

[
{
    "mdserver": "Medidata A",
    "mdport": "Port 1234",
    "mdstatus": true
},
{
    "mdserver": "Medidata B",
    "mdport": "Port 2345",
    "mdstatus": false
},
{
    "mdserver": "Medidata C",
    "mdport": "Port 3456",
    "mdstatus": true
}
]

For the dashboard, I want to create a function that checks whether any "mdstatus"-values are false. If any values are false, that means that the server is offline and the function should return "color="red"". I tried my best and this is what I came up with:

import React, { Component } from "react";
import { Card } from "tabler-react";
import "tabler-react/dist/Tabler.css";
import md from '../../data-input/MD.json'


function Mdalert() {
    const alert = Object.keys(md).some(k => !md.[k]);
    if (alert)
        return (
            <Card.Status color="red" />
        );
    else return (
    <Card.Status color="green" />
    );
}

export default class Mdserveralert extends Component {
    render() {
        return (
            <div>
               <Mdalert />
        </div>
        );
    }
}

However, I always get the "color="green"" value. Can any of you spot my mistake? Thank you very much for your time!

Upvotes: 0

Views: 1763

Answers (2)

Tasos
Tasos

Reputation: 2036

md is not an object, but an array, so use the some() directly on the md:

const alert = md.some(k => !k.mdstatus);

Upvotes: 1

Prateek Thapa
Prateek Thapa

Reputation: 4938

You could use the some method on an array.

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

You could check the docs here

You could check the working example here

md.some(k => !k.mdstatus)

It is better if you use Object.values with some. If md is an object. Object.values() returns an array whose elements are the values found on the object.

Object.values(md).some(k => !k.mdstatus)

Upvotes: 3

Related Questions