-3

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]
3
  • 4
    What you want is not a valid array, you probably want an object. Commented Jul 29, 2022 at 18:43
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 29, 2022 at 18:46
  • @SSM it is a valid array, just not recommended (and you can't declare it using an array literal) Commented Jul 29, 2022 at 20:25

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Actually you can use an array, but it will not function in expected ways.
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];
});

Comments

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

Comments

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]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.