Home > Software engineering >  combine array elements and send response
combine array elements and send response

Time:05-31

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).

CodePudding user response:

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);

CodePudding user response:

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.

CodePudding user response:

[].concat.apply([],[1,2,3].map(x => [1,2,3].map(y=> { return {'a': x, 'b':y}})))

CodePudding user response:

Const arr1 = [a1, a2, a3];
Const arr2 =[d1, d2, d3];
Const arr3 = [];

for(let i = 0;i<arr1.length;i  ){
  for(let b=0;b<arr2.length;b  ){
   return arr3.push({appid: arr1[i], dataid: arr2[b] })
}
}
  • Related