Nisha Nisha - 4 months ago 8
JSON Question

Array entries to be parsed to JSON

What would be the best approach - regex or something else?

I have following array:

[
"b1:number/1",
"b1:number/1/chest/85",
"b1:number/1/height/175",
"b1:number/1/hip/90",
"b1:number/1/category/bottoms/size_2/m",
"b1:number/1/category/bottoms/size_1/m",
"b1:number/1/category/bottoms/size_3/s",
]


I need to take brand b1 from the entry starting "b1:"
This should be parsed like:

{
"number": 1,
"category": "bottoms",
"height": "175",
"chest": 85,
"brand": "b1",
"hip": 90,
"size_1": "m",
"size_2": "m",
"size_3": "s"
}


Edit:
I need to parse only the data starting with "b1:number/". Incase of data like

[
"b1:another/somethingElse", //SHOULD NOT BE CONSIDERED
"b1:number/1",
"b1:number/1/chest/85",
"b1:number/1/height/175",
"b1:number/1/hip/90",
"b1:number/1/category/bottoms/size_2/m",
"b1:number/1/category/bottoms/size_1/m",
"b1:number/1/category/bottoms/size_3/s",
]

Answer

My idea was to use .reduce() to process each element in the array and add its values to an object. I .split() each item on the / character, then test how many pieces that produced in order to decide exactly what to do with it.

function processItem(item) {
  return item.reduce(function(a, v) {
    var parts = v.split("/");
    var b = parts[0].split(":");
    if (b[1] === "number") {
      switch(parts.length) {
        case 2:
          a[b[1]] = parts[1];
          a.brand = b[0];
          break;
        case 4:
          a[parts[2]] = +parts[3]; // note unary plus to convert to number
          break;
        case 6:
          if (!a[parts[2]])
            a[parts[2]] = parts[3];
          a[parts[4]] = parts[5];
          break;
      }
    }
    return a;
  }, {});
}

console.log(processItem([
    "b1:another/somethingElse",
    "b1:number/1",
    "b1:number/1/chest/85",
    "b1:number/1/height/175",
    "b1:number/1/hip/90",
    "b1:another/blah",
    "b1:number/1/category/bottoms/size_2/m",
    "b1:number/1/category/bottoms/size_1/m",
    "b1:number/1/category/bottoms/size_3/s",
]));