Combine the values of two arrays into object

前端 未结 5 1546
遥遥无期
遥遥无期 2021-01-21 08:43

I have two arrays:

array1 = [\"Bob\", \"John\", \"Dave\"];
array2 = [1, 2, 3];

Is there combine the two into a javascript array filled with obj

5条回答
  •  [愿得一人]
    2021-01-21 09:17

    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);

提交回复
热议问题