-4

consider this two arrays array y and array x i need to concatenates them but not after each other but be organised as in the form of array k the concatenate method just output them after each other

let x=['name','age','id'];
let y=['kyle',50,5050];
let k= x.concat(y);

the output i get is

k=['name','age','id','kyle',50,5050]

so how to merge them to get this output array

let k=['name':'kyle','age':50,'id':5050]
Mari
  • 7
  • 3

4 Answers4

1

This is possible, but not as an array. You need an object.

const x = ['name', 'age', 'id'];
const y = ['kyle', 50, '5050'];

const k = {};

x.forEach((element, index) => {
  k[element] = y[index];
});

console.log(k);
cdold
  • 129
  • 6
0

This should work for you Note: k is not an array, it's an object read about JavaScript object here

    let x = ['name', 'age', 'id'];
    let y = ['kyle', 50, 5050];
    let k = {};
    x.forEach((item, index) => {
        k[item] = y[index];
    });
   console.log(k);
Mohamed EL-Gendy
  • 566
  • 4
  • 11
0

Simply with map:

let x = ['name', 'age', 'id'];
let y = ['kyle', 50, 5050];
k= x.map((prop, i) => [prop, y[i]]);
console.log(k);// [["name","kyle"],["age",50],["id",5050]]
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
0

In fact, the javascript array doesn't look like this. We can have an array of objects or array of arrays

let keys=['name','age','id'];
let values=['kyle',50,5050];

var array = keys.map((el, i) => {
  return {[keys[i]]:values[i]}
}); // as array of objects

var array = keys.map((el, i) => {
  return [keys[i], values[i]];
}); // as array of arrays

of if you want a single object you can use

let obj = {};
keys.forEach((element, index) => {
  obj[element] = values[index];
});
Rahul Reghunath
  • 1,210
  • 13
  • 23