Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coordinating 2 drop-down dynamically in ReactJS

First post and I'll keep this short. I have a data fetched from an API and I want to, when you select let's say group A, then the second drop-down will display all the members from group A only.

These are the example response from the APIs I have access to. Note: there are many members in a group.

List groups

[
  "Group A",
  "Group B",
  "Group C"
]

Get members by groups

[
 {
   "group": "Group A",
   "name": " Jimmy"
 }
]

Get all members

[
 {
   "group": "Group A",
   "name": " Jimmy"
 },

 {
   "group": "Group B",
   "name": " Johnny"
 },
 {
   "group": "Group C",
   "name": " James"
 }
]

So how can I arrange these data into something like

groups: ["Group A", "Group B", "Group C"]
members: {
          Group A: ["Jimmy"],
          Group B: ["Johnny"],
          Group C: ["James"]
         }
like image 358
Quick Ly Lee Avatar asked May 19 '26 03:05

Quick Ly Lee


2 Answers

You can manually add members in your group as follows

let data = [
 {
   "group": "Group A",
   "name": " Jimmy"
 },

 {
   "group": "Group B",
   "name": " Johnny"
 },
 {
   "group": "Group C",
   "name": " James"
 },
 {
   "group": "Group C",
   "name": " Simon"
 }
]

let groupData = {}
data.forEach(item => {
  if (groupData[item.group]) {
    if (groupData[item.group].indexOf(item.name) === -1) {
      groupData[item.group].push(item.name)
    }
  } else {
    groupData[item.group] = [item.name];
  }
});

console.log("members: ", groupData)
console.log("groups: ", Object.keys(groupData))

// Or you could do the same thing with reduce and es6 conventions
const reducedData = data
  .reduce((acc, item) =>
    (acc[item.group] && acc[item.group].indexOf(item.name) === -1)
  	      ? ({...acc, [item.group]: acc[item.group].concat(item.name)})
  	      : ({...acc, [item.group]: [item.name]}), 
  {});
console.log("members: ", reducedData)
console.log("groups: ", Object.keys(reducedData))
like image 51
Prasanna Avatar answered May 20 '26 16:05

Prasanna


Here's the code to restructure that data:

let list = [
 {
   "group": "Group A",
   "name": " Jimmy"
 },

 {
   "group": "Group B",
   "name": " Johnny"
 },
 {
   "group": "Group C",
   "name": " James"
 }
]

let Restructure = (list) => {
  let newList = {}
  list.forEach(i => {
    newList[i.group] = [i]
  })
  
  return newList
}

console.log(Restructure(list))
like image 21
Nick Avatar answered May 20 '26 17:05

Nick