I have two arrays array1 and array 2.Array1 have values with a key name "discount_price" and array2 have values with key name "regular_price". eg: discount_price_array, regular_price_array
When i merge them using array merge i get a single array with combined values. i.e if array1 has 10 elements and array2 has 10 elements it merges into an array with 20 elements. merged_array.
what i want is instead an array with eg:
array{"discount_price":10,"regular_price":2},
array{"discount_price":4,"regular_price":3},
How can i achieve this ?
$(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
)
CodePudding user response:
Using map
and 'destructuring (...)'
map
: lets to iterate over an array and return the same length new array, where you decide what will be returned in every iteration.
(...) spread
, allows you to spread the (outer properties) properties in a new object or array, you are basically assigning all object properties to new object, since you are spreading two object in the same new object, they are being merged.
// 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);
simple 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);