简体   繁体   中英

Creating an array from 1 keys array and 1 values array in JavaScript?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM