I am trying to extract data from an auto-generated object by cleaning up duplicates and concatenating any additional entries. Here is a simplified example:
const categories = [{
category: "mammal",
options: ["horse", "cow"],
}, {
category: "mammal",
options: ["pig", "cow"],
}, {
category: "gender",
options: ["male"],
}, {
category: "mammal",
options: ["cow"],
}, {
category: "mammal",
options: ["pig"],
}, {
category: "gender",
options: ["female"],
}];
The desired output should be formatted like this:
mammal>horse;cow;pig/gender>male;female/
I have attempted to loop through the object array to compare properties but struggle with appending unique options under each category without duplications.
const newArr = [];
for (let i = 0; i < categories.length; i++) {
categoryIsInArray = newCat.indexOf(categories[i].category) !== -1;
if (categoryIsInArray === true) {
// logic for handling options
}
else {
newArr.push(categories[i].category)
}
}
However, my current method only produces a limited array:
["mammal","gender"]
I believe I need to iterate over the options within each category and add them accordingly. Here is my attempt:
const newArr = [];
for (let i = 0; i < categories.length; i++) {
categoryIsInArray = newCat.indexOf(categories[i].category) !== -1;
if (categoryIsInArray === true) {
for (let j = 0; j < categories[i].options.length; j++) {
optionIsInArray = newCat.indexOf(categories[i].options[j]) !== -1;
if(optionIsInArray === false) {
newCat.push(categories[i].options)
}
}
}
else {
newArr.push(categories[i].category)
}
}
Unfortunately, this approach has not yielded the desired result and has mixed up the structure. Any advice on how I can modify this to achieve my goal?