I am trying to make this 2 different array
array1 = ["ramu", "raju", "ravi"] ;
array2 = [10, 20, 30];
want to be in single array name
arrayNeed =[{name:"ramu",amt:10},{name:"raju",amt:20},{name:"ravi",amt:30}];
I am trying to make this 2 different array
array1 = ["ramu", "raju", "ravi"] ;
array2 = [10, 20, 30];
want to be in single array name
arrayNeed =[{name:"ramu",amt:10},{name:"raju",amt:20},{name:"ravi",amt:30}];
You are looking to zip array1 and array2. You should use map for this:
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
array1 = ["ramu", "raju", "ravi"] ;
array2 = [10, 20, 30];
arrayNeed = array1.map((x, i) => ({name: x, amt: array2[i]}))
Related to:
You can simply run forEach
on the first array. This will accept a callback function with two args: item(one at a time), index of that item in the array.
Since you'll have the index
, you can simply add a key named amt
with a value of array2
's value at index
Try this
array1 = ["ramu", "raju", "ravi"] ;
array2 = [10, 20, 30];
arrayNeed = [];
array1.forEach((item, index) => {
arrayNeed.push({ name: item, amt: array2[index] });
})
A short-hand syntax could also be:
arrayNeed = array1.map((item, index) => ({ name: item, amt: array2[index] }))
or
arrayNeed = array2.map((item, index) => ({ amt: item, name: array1[index] }))