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} ] 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); You could use an object and iterate the keys and the values.
var array1 = ["Bob", "John", "Dave"], array2 = [1, 2, 3], object = { meta: array1, value: array2 }, result = Object.keys(object).reduce(function (r, k) { object[k].forEach(function (a, i) { r[i] = r[i] || {}; r[i][k] = a; }); return r; }, []); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } Assuming you're using Chrome, you could do:
const combined = array1.map((name,i) => ({meta: name, value: array2[i]}))
const and the fat arrow syntax could be trouble.const but not arrow functions. MS Edge supports both.