這是我在單擊表單提交按鈕時發送的請求正文:
{
"name":'test',
"age":'test1',
"appId":[10,20,30],
"dataId":[1,2,3]
}
我想這樣修改它:
[
{ 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 },
]
這需要使用 Javascript (ES6) 來完成。
uj5u.com熱心網友回復:
這是笛卡爾積:
const cartesian = (a, b) => a.flatMap(appid => b.map(dataid => ({appid, dataid})));
console.log(cartesian(["a", "b", "c"], [1, 2, 3]));
在下面的評論中,您提供了一個圍繞兩個輸入陣列的物件包裝器,并希望將其他物件屬性復制到結果物件中。
那么它就變成了:
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);
uj5u.com熱心網友回復:
let combinedArray = [];
array1.forEach((element, index) => {
let batch = [];
array2.forEach((element2, index2) => {
batch.push({
appid: element,
dataid: element2
});
});
combinedArray.push(...batch);
});
沿著這些思路。假設陣列長度相同且順序正確,這似乎是最簡單的方法。您可以改用 for 回圈。
實際上,這似乎也不是正確的解決方案。我不確定你想用你的例子實作什么模式,所以我會這樣。您可以根據需要調整演算法。
編輯是因為我重新閱讀了這個問題。
uj5u.com熱心網友回復:
[].concat.apply([],[1,2,3].map(x => [1,2,3].map(y=> { return {'a': x, 'b':y}})))
uj5u.com熱心網友回復:
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] })
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483809.html
標籤:javascript 数组 反应 多维数组 ecmascript-6
上一篇:商店中的物品數量Java