0

I have two arrays that look like this:

    ["Test", "Test2", "Test3"]
    ["ID1", "ID2", "ID3"]

I need to create an array from the above arrays that looks like this:

    ["Test": "ID1", "Test2": "ID2", "Test3": "ID3"]

I'm currently doing this but this is not correct:


    var new_arr = [];
    var something = 'Test';
    var something2 = 'ID1';
    
    var n = ''+something+':'+something2+'';
    
    new_arr.push(n);

This code produces the following which is not right:

    ["Test:ID1","Test2:ID2"]

Could someone please advise on this?

4
  • 1
    Your desired output is not valid JavaScript. Are you sure you want an array? Commented Oct 5, 2021 at 10:29
  • 1
    You need to make an array of objects, the syntax you provided is not valid. Something like this is what you are looking for I think [{"Test": "ID1"}, {"Test2": "ID2"}, {"Test3": "ID3"}] Commented Oct 5, 2021 at 10:30
  • @ToniMichelCaubet, yes thats it. thats what I need to do. Commented Oct 5, 2021 at 10:30
  • check @trincot answer, then ;) Commented Oct 5, 2021 at 10:36

1 Answer 1

4

What you want seems to be a better fit for a plain object, not an array.

For that you can use map and Object.fromEntries:

let keys = ["Test", "Test2", "Test3"];
let values = ["ID1", "ID2", "ID3"];

let obj = Object.fromEntries(keys.map((key, i) => [key, values[i]]));

console.log(obj);

Or if you need separate objects, each with just one key/value pair, then use a computed property name in an object literal:

let keys = ["Test", "Test2", "Test3"];
let values = ["ID1", "ID2", "ID3"];

let arr = keys.map((key, i) => ({ [key]: values[i] }));

console.log(arr);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.