Home > Net >  Group JSON values to display in React Dropdown list
Group JSON values to display in React Dropdown list

Time:11-10

I'm getting my JSON data as such:

{ 
   "cars": [
       {
          "make":"BMW",
          "model":"X3",
          "Lot":"Used"
       },
       {
          "make":"BMW",
          "model":"520",
          "Lot":"Used"
       },
       {
          "make":"Mercedes",
          "model":"550",
          "Lot":"New"
        },
        {
           "make":"Mercedes",
           "model":"C400",
            "Lot":"Used"
         }
     ]
}
        

I want to group them by the make to show in my dropdown list like so:

 BMW
     Used
        X3
       520
 Mercedes
      New
         550
      Used
         C400

I'm currently using this on a React page and I have the dropdown populated, I'd like to group them as such instead of showing everything on one line for each record

CodePudding user response:

You could Array#reduce over it group by make, model and Lot keys.

const group = (arr) => arr.reduce((acc, { make, Lot, model }) => {
  if (!acc[make]) {
     acc[make] = {};
  }
  
  (acc[make][Lot] || (acc[make][Lot] = [])).push(model);

  return acc;
}, {});

const json={"cars":[{"make":"BMW","model":"X3","Lot":"Used"},{"make":"BMW","model":"520","Lot":"Used"},{"make":"Mercedes","model":"550","Lot":"New"},{"make":"Mercedes","model":"C400","Lot":"Used"}]}

console.log(group(json.cars));

CodePudding user response:

@topched Right now, I'm just binding the data from my API. like so:

const getAllCars = () => {
   allCars.GetAllCars()
     .then((response) => {
        setallCars(response.data)
    })
      .catch((e) => { console.log(e)}

}





return (
   <select> 
    <option value ='0'>
      { carTypes.map(data => (
         <option
            value={data.make}
          >
          { data.make }
         </option>
       )
  )

like I mentioned, I'm just binding the data, without the grouping.

  • Related