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"]
}
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With