'Merging the object having array in JSONata into array of objects
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"
}]}
Solution 1:[1]
{
"skus":skus.$.b.
{
"a": %.a,
"c":%.c,
"b":$
}
}
This is the JSONata spec. Try it https://try.jsonata.org/P5E2v0FNn
Solution 2:[2]
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);
Solution 3:[3]
$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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Suraj Rao |
| Solution 2 | Syed M Sohaib |
| Solution 3 | Siddharth Sarda |

