Home > OS >  How can I add another information in an fetch API array?
How can I add another information in an fetch API array?

Time:12-02

So I'm trying to create a BarChart for the category, and each category will have a respective color. I map this information from the MongoDB.

  const [topDepartment,setTopDepartment] = useState([])
  useEffect(() =>{
   
    const getTopDepartment = async () =>{ 
      try {
        const res = await publicRequest.get(`/order/departments`)
        setTopDepartment(res.data)
        setLoading(false)
      } catch (error) {
        
      }
    }
    getTopDepartment()

  },[setTopDepartment])

This is the data I received

[
    {
        "total": 4,
        "category": "CAHS"

    },
    {
        "total": 2,
        "category": "CEIS"
    }
]

So what I'm trying to accomplish right now is , how can I add another information inside the objects, like this.

 const updatedData =  [
    {
        "total": 4,
        "category": "CAHS"
        "color": "purple"

    },
    {
        "total": 2,
        "category": "CEIS"
        "color": "green"

    }
]

Like in this image, the Bar will change it's color depending on its category enter image description here

CodePudding user response:

You can just loop over the data you recieved and add colors accordingly,

const updatedData = res.data.map(el => {
    el.color = "green"
    return el;
});

You can also add the color conditionally inside the map

CodePudding user response:

You can iterate the array in map function and add another property to the object

const resWithColors = res.data.map((object) => {
   switch(object.category){
     case 'CEIS':
        object['color'] = "green";
        break;
     .
     .
     .
     default: 
       object['color'] = "red";
   }
   return object;
})
  • Related