Home > Net >  JavaScript map a JSON response into a new Array
JavaScript map a JSON response into a new Array

Time:08-06

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"},
            ],
    }
]

CodePudding user response:

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;
    }
  , {}) 
)

  • Related