0

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

1
  • Please post at least an attempt at reducing the data into the shape that you need. This isn't a place to just get solutions without an attempt. Commented Nov 9, 2022 at 19:44

2 Answers 2

1

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));

Sign up to request clarification or add additional context in comments.

Comments

0

@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>
      )
 )

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.