Ryan Bell
Ryan Bell

Reputation: 149

JavaScript map a JSON response into a new Array

I have a script that pulls responseText from a website and parses it into JSON. An example of the output looks like this:

ctiResponse = [
    "Category / Type1 / Item1",
    "Category / Type1 / Item2",
    "Category / Type1 / Item2",
    "Category / Type1 / Item3",
    "Category / Type2 / Item1",
    "Category / Type2 / Item2",
    "Category / Type2 / Item2",
    "Category / Type2 / Item3",
    "Category / Type3 / Item1",
    "Category / Type3 / Item2",
    "Category / Type3 / Item2",
    "Category / Type3 / Item3",
];

I think the .map() function is what I need to use to accomplish my end result, but I'm not sure how to go about it. I'd like to create another array from the parsed JSON response that would end up like the following. Note that the parsed JSON response has repeated Items, and I only need those once in the second array.

let ctis = [
    {
        "Category": [
            "Type1": {"Item1", "Item2", "Item3"},
            "Type2": {"Item1", "Item2", "Item3"},
            "Type3": {"Item1", "Item2", "Item3"},
            ],
    }
]

Upvotes: 0

Views: 143

Answers (1)

Mateusz Rorat
Mateusz Rorat

Reputation: 127

const ctiResponse = [
    "Category / Type1 / Item1",
    "Category / Type1 / Item2",
    "Category / Type1 / Item2",
    "Category / Type1 / Item3",
    "Category / Type2 / Item1",
    "Category / Type2 / Item2",
    "Category / Type2 / Item2",
    "Category / Type2 / Item3",
    "Category / Type3 / Item1",
    "Category / Type3 / Item2",
    "Category / Type3 / Item2",
    "Category / Type3 / Item3",
];

console.log(
  ctiResponse.reduce(
    (obj, line) => {
      const [category, type, item] = line.split(' / ');
      obj[category] = {...obj[category]}
      obj[category][type] = [...new Set([...obj[category][type] || [], item])];
        return obj;
    }
  , {}) 
)

Upvotes: 1

Related Questions