Home > Net >  How to sort by Key of Json and display them in React.js?
How to sort by Key of Json and display them in React.js?

Time:10-05

Currently, I'm making a system that can control home electrical equipment on the web. Backend is ready I am making a front end with React.js.

Below is the Json data of the electrical equipment I want to sort by "room_name" Key I would like to display it divided into boxes like the picture but I don't know how. (I'm using Bootstrap by the way.)

enter image description here

Json

{
    "attributes": {
        "camera": [
            {
                "entity_id": "camera_2",
                "object_id": "AMC05723DA911E755D",
                "room_name": "Garage",
            },
            {
                "entity_id": "camera_1",
                "object_id": "AMC0570066109434BF",
                "room_name": "Main",
            },
            {
                "entity_id": "camera_4",
                "object_id": "AMC057ED147BD72134",
                "room_name": "Lobby",
            },
            {
                "entity_id": "camera_3",
                "object_id": "Z104E0A3476D0",
                "room_name": "Garage",
            }
        ],
        "climate": [
            {
                "entity_id": "Honeywell Touchscreen Thermostat 10",
                "object_id": "0x0008_10",
                "room_name": "Main",
            }
        ],
        "cover": [
            {
                "entity_id": "Garadget",
                "room_name": "Garage",
            }
        ],
        "light": [
            {
                "entity_id": "A19_W_60_01",
                "object_id": "8984750156480003986",
                "room_name": "unused",
            },
            {
                "entity_id": "Device_01",
                "object_id": "9518399593889591551",
                "room_name": "unused",
            },
            {
                "entity_id": "A19_TW_60_01",
                "object_id": "9518399593889740169",
                "room_name": "Main",
            },
            {
                "entity_id": "Sales_Hue_color_lamp_2",
                "object_id": "4",
                "room_name": "Main",
            },
            {
                "entity_id": "Sales_Hue_white_lamp_1",
                "object_id": "5",
                "room_name": "Main",
            },
            {
                "brightness": 72,
                "entity_id": "Sales_Hue_white_lamp_2",
                "object_id": "6",
                "rgb_color": [],
                "room_name": "Main",
                "state": "On",
                "is_failed": false,
                "disabled": false
            }
        ],
        "lock": [
            {
                "entity_id": "Deadbolt 27",
                "object_id": "0x0600_27",
                "room_name": "Garage",

            },
            {
                "entity_id": "Deadbolt26",
                "object_id": "0x0469_26",
                "room_name": "Main",
            }
        ],
        "sensor": [
            {
                "entity_id": "Door Sensor 38",
                "object_id": "0x0082_38",
                "room_name": "Unassigned Devices",
            },
            {
                "entity_id": "Water Leak 23",
                "object_id": "0x2003_23",
                "room_name": "Unassigned Devices",
            },
            {
                "entity_id": "General Purpose 24",
                "object_id": "0x2002_24",
                "room_name": "Unassigned Devices",
            }
        ],
        "switch": [
            {
                "entity_id": "Smart Plug 40",
                "object_id": "0xff0c_40",
                "room_name": "Unassigned Devices",
            }
        ],
    }
}

React.js

import React, { useState, useEffect, useCallback, onClick} from 'react';
import axios from 'axios';

const DiscoverCondoRoom = () => {
    
    const [camera, setCamera] = useState([]);
    const [climate, setClimate] = useState([]);
    const [cover, setCover] = useState([]);
    const [light, setLight] = useState([]);
    const [lock, setLock] = useState([]);
    const [sensor, setSensor] = useState([]);
    const [state, setState] = useState([]);
    const [switch2, setSwitch] = useState([]);

    const { entity_id } = useParams();

    const getDevices = async(data) => {
      await axios.get('https:/xxx.com/discover',
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${cookies.get('accesstoken')}`
          },
        })
        .then(result => {
          console.log(result.data)
          setCamera(result.data.attributes.camera);  
          setClimate(result.data.attributes.climate);  
          setCover(result.data.attributes.cover);  
          setLight(result.data.attributes.light);  
          setLock(result.data.attributes.lock);  
          setSensor(result.data.attributes.sensor);  
          setState(result.data.attributes.state);  
          setSwitch(result.data.attributes.switch); 
        })
        .catch(err => {
          console.log(err);
        });
    }
    
    useEffect(() => {
      getDevices();
    },[]);




  return (

    ?????
    
    
  );
}
export default DiscoverCondoRoom;

CodePudding user response:

You can do it easily by creating a big component named Services here[where all boxes will belong]. Then pass the value retrieved from the Backend in the Service component[every small box, named: Garage, Lobby,.. ..]. Hope you get the concept.

const Services = () => {

    const [services, setServices] = useState([]);

    useEffect( ()=>{
        fetch('https://myApi.herokuapp.com/service')
        .then(res => res.json())
        .then(data => setServices(data));
    }, [])

    return (
        <div id="services" className='container'>
            <div className="row">
            <h1>My Big Service component</h1>
            <div className="services-container">
            {
                services.map(service => <Service
                    key={service._id}
                    service={service}
                >
                </Service>)
            }
            </div>
            </div>
        </div>
    );
};

export default Services;

This is a small component of the Garage, Lobby, Main,... ...

const Service = ({service}) => {
    const {_id, name, img, description, price} = service;

    return (
        <div className='service'>
            <img className='w-100' src={img} alt="" />
            <h2>{name}</h2>
            <p>Price: {price}</p>
            <p>description}</p>
            <button onClick={...}>My button:{name}</button>
        </div>
    );
};

export default Service;

CodePudding user response:

I would create a react component called Room. It could looks something like this

const Room = (name, devices) => {
    return (
        <div>
            <h1>{name}</h1>
            {devices.map(device => {
                return <div>...</div>
            })}
        </div>
    )
}

Then I would restructure your json result so it looks something like the following. You can do this multiple ways, but the most straight forward may be to loop through the entities and get a set/list of all of the unique rooms. Then create the restructured object base/outline using that list (without the devices array populated yet). So for each room, add an object ({"name": thename, "devices": []}) to a list. Then loop again through the list of entities and add the entity to the corresponding room. This is a relatively inefficient way of doing it, so you can improve this if you'd like.

[
   {
       "name": "some room name",
       "devices": [
         {
            "entity_id": "Honeywell Touchscreen Thermostat 10",
            "object_id": "0x0008_10",
         },
         {
            "entity_id": "Honeywell Touchscreen Thermostat 10",
            "object_id": "0x0008_10",
         }
       }
   },
   {
       "name": "some room name",
       "devices": [
         {
            "entity_id": "Honeywell Touchscreen Thermostat 10",
            "object_id": "0x0008_10",
         },
         {
            "entity_id": "Honeywell Touchscreen Thermostat 10",
            "object_id": "0x0008_10",
         }
       }
   } 
]

Lastly in your main app page after creating the new restructured object (and setting it as a state). You can loop through the object and have a room component for each. It could look something like this.

{restructuredObject.map( o => {
    return <Room name={o.name} devices={o.devices} />
})}
    
  • Related