Home > Mobile >  JS push arrays to main array with key name
JS push arrays to main array with key name

Time:02-10

I have solidIcons which contains:

['book', 'apple', 'smile', 'pencil']

and regularIcons:

['flower', 'clock', 'house', 'bird']

I want to create the following array from the two:

{ 
  'solid-icons': ['book', 'apple', 'smile', 'pencil'], 
  'regular-icons': ['flower', 'clock', 'house', 'bird'], 
}

The goal is to be able to use map to loop through either solid-icons or regular-icons.

I'm trying:

let allIcons = [];

allIcons["solid-icons"] = solidIcons;
allIcons["regular-icons"] = regularIcons;

This is creating

0: [solid-icons: Array()] 
1: [regular-icons: Array()] 

The issue is that O cannot simply access an array group with allIcons["solid-icons"] I have to use the index allIcons[0]. How can i create the array in such a way that i can use the solid-icons or regular-icons to access without the index.

CodePudding user response:

let allIcons = [] - this is array, you need let allIcons = {} instead

let allIcons = {};

allIcons["solid-icons"] = solidIcons;
allIcons["regular-icons"] = regularIcons;

CodePudding user response:

I think you can just use object literal:

let allIcons = { 
  'solid-icons': ['book', 'apple', 'smile', 'pencil'], 
  'regular-icons': ['flower', 'clock', 'house', 'bird'], 
}

You are not creating an array but object.

  • Related