Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine the values of two arrays into object

Tags:

javascript

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}
]
like image 456
eeetee Avatar asked Mar 10 '23 18:03

eeetee


2 Answers

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]
  }
));
like image 100
Mike Cluck Avatar answered Mar 12 '23 06:03

Mike Cluck


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);
like image 33
kind user Avatar answered Mar 12 '23 06:03

kind user