我有兩個陣列 array1 和陣列 2.Array1 具有鍵名為“discount_price”的值,array2 具有鍵名為“regular_price”的值。例如: discount_price_array, regular_price_array
當我使用陣列合并合并它們時,我得到一個帶有組合值的陣列。即如果 array1 有 10 個元素,array2 有 10 個元素,它合并成一個有 20 個元素的陣列。合并陣列。
我想要的是一個陣列,例如:
array{"discount_price":10,"regular_price":2},
array{"discount_price":4,"regular_price":3},
我怎樣才能做到這一點?
$(values).each(function(key, value) {
//console.log(value);
if( value.discount_price !==undefined){
discount_price_array.push({ discount_price: value.discount_price })
}
});
$(values).each(function(key, value) {
//console.log(value);
if( value.regular_price !==undefined){
regular_price_array.push({ regular_price: value.regular_price })
}
});
var finalarray =$.merge(discount_price_array,regular_price_array
)
uj5u.com熱心網友回復:
使用map和'解構(...)'
map: 讓我們遍歷一個陣列并回傳相同長度的新陣列,您可以在其中決定每次迭代將回傳什么。
(...) spread,允許您在新物件或陣列中傳播(外部屬性)屬性,您基本上是將所有物件屬性分配給新物件,因為您在同一個新物件中傳播兩個物件,它們正在合并.
// if both of them have the same length
let arr1 = [{'property1': 10 }, {'property1': 10 },];
let arr2 = [{'property2': 20 }, {'property2': 20 },];
let result = arr1.map((object, index)=> ({...object, ...arr2[index] }));
console.log(result);
簡單的 map only
// if you want to pick which property to assign
let arr1 = [{'property1': 10 }, {'property1': 10 }];
let arr2 = [{'property2': 20 }, {'property2': 20 }];
let result = arr1.map((object, index)=> {
object['property2'] = arr2[index]['property2'];
return object;
});
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/391072.html
標籤:javascript 查询
