This is my request body which I am sending on click of form submit button:
{
"name":'test',
"age":'test1',
"appId":[10,20,30],
"dataId":[1,2,3]
}
I want to modify it this this:
[
{ name: "test", age: "test1", appId: 10, dataId: 1 },
{ name: "test", age: "test1", appId: 10, dataId: 2 },
{ name: "test", age: "test1", appId: 10, dataId: 3 },
{ name: "test", age: "test1", appId: 20, dataId: 1 },
{ name: "test", age: "test1", appId: 20, dataId: 2 },
{ name: "test", age: "test1", appId: 20, dataId: 3 },
]
This needs to be done using Javascript (ES6).
This is a Cartesian product:
const cartesian = (a, b) => a.flatMap(appid => b.map(dataid => ({appid, dataid})));
console.log(cartesian(["a", "b", "c"], [1, 2, 3]));
In a comment below you provide an object wrapper around the two input arrays, and want the other object properties to be copied into the result objects.
So then it becomes:
const cartesian = (obj, a, b) =>
obj[a].flatMap(x => obj[b].map(y => ({...obj, [a]: x, [b]: y}) ));
const response = {name:'test', age:'test1', appId:[10,20,30], dataId:[1,2,3]};
const result = cartesian(response, "appId", "dataId");
console.log(result);
let combinedArray = [];
array1.forEach((element, index) => {
let batch = [];
array2.forEach((element2, index2) => {
batch.push({
appid: element,
dataid: element2
});
});
combinedArray.push(...batch);
});
Something along these lines. Seems like the easiest way to do this assuming arrays are the same length and in the right order. You can use for loop instead.
Actually, that doesn't seem like the right solution either. I'm not sure what pattern you are trying to achieve with your example, so I will leave it like this. You can adjust the algorithm to your needs.
Edited because I re-read the question.
[].concat.apply([],[1,2,3].map(x => [1,2,3].map(y=> { return {'a': x, 'b':y}})))