Skip to content
Advertisement

pushing string[array] instead of ‘string’ to array in plain javascript

I have this code

let array = [];
const datas = [
 'name1',
 'name2',
 'name3',
];
 
async function getData() {
    datas.forEach((data) => {
      let myData = data.name;
      if(!array.includes(myData)){
        array.push(myData);
      }
    })

    let result = await array;
    
    console.log('Result', result);
};

getData();

that returns an array that contains strings like

['name1','name2', 'name3']

And I would like to make all of the array indexes arrays themselves, so I can later push data in the array’s indexes, like

['name1': [], 'name2': [], 'name3': []]

Does somebody know how to do this in plain javascript ?

Advertisement

Answer

If i understood well, seems you need something like this

let obj = {};
const datas = [
 'name1',
 'name2',
 'name3',
];
 
function getData() {
    datas.forEach((data) => {
      obj[data] = []
    })

    console.log('Result', obj);

};

getData();
Result { name1: [], name2: [], name3: [] }

tip: Array keys can be only indexes

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement