I have two arrays and I want to form an array of objects such that the new array of obj has two keys with first key being filled with elements of first array and second key having arrays elements of second array. Can this be done using the map function. I found the closest answer as this:- Merge two arrays into an array of objects with property values
eg.:-
ar1=[];
ar2=[];
armixed=[{ar1element,ar2element},{}......]
But it uses angular JS I just want to use pure JS.
I have two arrays and I want to form an array of objects such that the new array of obj has two keys with first key being filled with elements of first array and second key having arrays elements of second array. Can this be done using the map function. I found the closest answer as this:- Merge two arrays into an array of objects with property values
eg.:-
ar1=[];
ar2=[];
armixed=[{ar1element,ar2element},{}......]
But it uses angular JS I just want to use pure JS.
Share Improve this question edited May 15, 2023 at 16:38 isherwood 61.1k16 gold badges120 silver badges168 bronze badges asked Jun 7, 2018 at 12:46 heartyhearty 7315 gold badges10 silver badges15 bronze badges 6 | Show 1 more comment2 Answers
Reset to default 17I'm not sure what your output should be but the one you provided seems invalid. I have modified the output format to be valid.
For the task you have the solution is to zip
the arrays, however, JS has no inbuilt zip
function, so we can emulate it via map
function:
var ar1 = ['a1', 'a2', 'a3', 'a4', 'a5'];
var ar2 = ['b1', 'b2', 'b3', 'b4', 'b5'];
var armixed = ar1.map(function(x, i) {
return [x, ar2[i]]
});
console.log(armixed);
Output will be:
armixed = [
["a1", "b1"]
["a2", "b2"]
["a3", "b3"]
["a4", "b4"]
["a5", "b5"]
]
If you want objects in your output (rather than arrays), you can just edit the return statement above to something like:
return { categories: x, catid: ar2[i] }
Nowadays we can write this to make an array of objects from multiple arrays
const price = ['100', '200', '300', '400', '500'];
const qty = ['50', '40', '30', '20', '10'];
const result = price.map((price,i) => ({price, qty:qty[i]}))
console.log(result)
Can this be done using the map function
? Already answered with map in referrer question. – Nishant Dixit Commented Jun 7, 2018 at 12:51