I have two arrays:
array1 = ["Bob", "John", "Dave"];
array2 = [1, 2, 3];
Is there combine the two into a javascript array filled with objects that looks like:
[
  {meta: 'Bob', value: 1 },
  {meta: 'John', value: 2},
  {meta: 'Dave', value: 3}
]
                Let's break it down.
You have two arrays of equal length and you want to extract a value from each.
// Could also do array2.length since they're the same size
for (var i = 0; i < array1.length; i++) {
  var val1 = array1[i];
  var val2 = array2[i]
}
and you want to create an object using those two values
for (var i = 0; i < array1.length; i++) {
  var val1 = array1[i];
  var val2 = array2[i]
  var obj = {
    meta: val1,
    value: val2
  };
}
Finally, you want to store each of those generated objects in an array
var result = [];
for (var i = 0; i < array1.length; i++) {
  var val1 = array1[i];
  var val2 = array2[i]
  var obj = {
    meta: val1,
    value: val2
  };
  result.push(obj);
}
And now you have your result!
You could rewrite this in a number of ways. For example:
var result = array1.map(function(val1, index) {
  return {
    meta: val1,
    value: array2[index]
  };
});
or if you're in an environment which supports it:
let result = array1.map((val1, index) => (
  {
    meta: val1,
    value: array2[index]
  }
));
                        It's one of the ways how to achieve it. You can use Array#forEach function to iterate over every element from array1. Then, create empty object and set specified properties - in your case: meta and value. Then - assign elements to it and just push it into the arr variable.
var array1 = ["Bob", "John", "Dave"],
    array2 = [1, 2, 3],
    arr = [];
array1.forEach(function(v,i){
  var obj = {};
  obj.meta = v;
  obj.value = array2[i];
  arr.push(obj);
});
console.log(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With