Merging the object having array in JSONata into array of objects

Viewed 138

I need to merge the array item to object using JSONata If my input is

{"skus":[
  {
    "a":1,
    "c":3,
    "b":["n"]
  },
  {
    "a":6,
    "c":7,
    "b":["f","h"]
  }]}

I need output as below. I need it to be expanded within same object

{"skus":[
  {
    "a":1,
    "c":3,
    "b":"n"
  },
  {
    "a":6,
    "c":7,
    "b":"f"
  },
  {
    "a":6,
    "c":7,
    "b":"h"
  }]}

3 Answers

You can achieve the above result using reduce

let json = {"skus":[
  {
    "a":1,
    "c":3,
    "b":["n"]
  },
  {
    "a":6,
    "c":7,
    "b":["f","h"]
  }]};



json.skus = json.skus.reduce((acc, item) => {
  if(typeof item.b === "object"){
    let a = item.b.map(i =>{
      let out = {...item};
      out.b = i;
      return out; 
    })
    return acc.concat(a);
  }else{
    return acc.concat(item);
  }
},[]);

console.log(json);

  $arrayOfArrays := $map(skus, function($sku) {
    $map($sku.b, function($val) { 
      {"a": $sku.a, "c": $sku.c, "b" : $val}
    })
  });
  
  {"skus": $reduce($arrayOfArrays,$append)}

Assuming that its always "b" which is the array, this jsonata expression should work. Screenshot attached below from here

enter image description here

Related