简体   繁体   中英

javascript array or objects how to add multi items with same key

javascript array how to add multiples values for same key

I want to referre to root menu with it's sub menu

like the following

menu and sub menu

root menu 0 ids -> 1,2,3
sub menu 1 ids -> 5,7
sub menu 2 ids -> 9

arr[0]=[1,2,3];
arr[1]=[5,7];
arr[2]=[9];

I try

arr[0].push(1);
arr[0].push(2);

arr[0] store last value only 2

if array not do that can do same exmple with array of objects

Sorry, I'm not quite sure what you are expecting. Try the code blow.

Example 1

 let arr = []; let rootMenu = [1,2,3]; let subMenu_1 = [5,7]; let subMenu_2 = [9]; arr.push(rootMenu); arr.push(subMenu_1); arr.push(subMenu_2); console.log(arr);

Example 2

 let arr = Array.from({length:3}, () => []); console.log(arr); // Output: [[], [], []] arr[0].push(1); arr[0].push(2); arr[0].push(3); arr[1].push(5); arr[1].push(7); arr[2].push(9) console.log(arr);

Example 3

 let arr = []; arr[0] = []; arr[0].push(1); arr[0].push(2); arr[0].push(3); arr[1] = []; arr[1].push(5); arr[1].push(7); arr[2] = []; arr[2].push(9) 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