简体   繁体   中英

how to assign values in array key and value pair one array to another array in javascript?

var a = ['lkg','ukg'];
var b = ['lkg_stud_name','ukg_stud_name'];

I want to below like this?

 var c =(
        ['lkg','lkg_stud_name'],
        ['ukg','ukg_stud_name']
    );

For example a[0] and b[0] in same row, a[1] and b[1] in same row in array c .

Please help me

You can do that fairly easily by mapping through the values of one array assuming they are both the same length:

 var a = ['lkg','ukg']; var b = ['lkg_stud_name','ukg_stud_name']; var c = a.map((item, index) => [item, b[index]]) console.log(c) 

An alternative is using the function Array.from .

This is assuming both arrays have the same length.

 var a = ['lkg','ukg'], b = ['lkg_stud_name','ukg_stud_name'], c = Array.from({length: a.length}, (_, i) => [a[i], b[i]]); console.log(c); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Wider compatible approach using for-loop :

 var a = ['lkg','ukg'], b = ['lkg_stud_name','ukg_stud_name'], c = []; for (var i = 0; i < a.length; i++) c.push([a[i], b[i]]); console.log(c); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

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