How to create new array with key and value with 2 arrays?

Viewed 359

I have 2 array, one for key and other for value.

Want create new array with these arrays.

key: [01, 02, 03]
value: ["hi", "hello", "welcome"]
Output I need:

[ 
  {"key": "1","value":"hi"},
  {"key": "2","value":"hello"},
  {"key": "3","value":"welcome"} 
]    

How to get result by this way.?

My code:

output = key.map(function(obj, index){
      var myObj = {};
      myObj[value[index]] = obj;
      return myObj;
    })    

Result:

 [
 {"1","hi"},
 {"2","hello"},
 {"3","welcome"} 
    ]
4 Answers

    var myArray = [];  
    var keys = [45, 4, 9];  
    var cars = ["Saab", "Volvo", "BMW"];  
    cars.forEach(myFunction);  
    var txt=JSON.stringify(myArray);  
    document.getElementById("demo").innerHTML = txt;  
      
    function myFunction(value,index,array) {  
        var obj={ key : keys[index], value : value };  
        myArray.push(obj);  
    }  
    <p id="demo"></p>  

You could take an object with arbitrary count of properties amd map new objects.

var key = [1, 2, 3],
    value = ["hi", "hello", "welcome"],
    result = Object
        .entries({ key, value })
        .reduce((r, [k, values]) => values.map((v, i) => Object.assign(
            {},
            r[i],
            { [k]: v }
        )), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Here you have another apporach using reduce():

let keys = [01, 02, 03];
let values = ['hi', 'hello', 'welcome'];

let newArray = keys.reduce((res, curr, idx) => {
    res.push({'key': curr.toString(), 'value': values[idx]});
    return res;
}, []);

console.log(newArray);

Related