Martijn Kekistan
Martijn Kekistan

Reputation: 1

Pushing an object into an object under a certain key

I'm trying to achieve the following Array/Object,

[
 1:[{data:data},{data:data}]
]

How would this be achieved? I got thus far,

var data = [];
data['1'] = {data:data}

but this just overwrites.

Upvotes: 0

Views: 44

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138287

If i get you right you want to push objects into an array inside of an hashtable ( which can be easily implemented using an object in javascript). So we need an object first:

 const lotteries = {};

Now before storing data, we need to check if the relating array exists, if not we need to create it:

 function addDataToLottery(lottery, data){
   if(!lotteries[lottery]){ //if it doesnt exist
     lotteries[lottery] = [];  //create a new array
   }
   //As it exists definetly now, lets add the data
   lotteries[lottery].push({data});
 }

 addDataLottery("1", { what:"ever"});

 console.log(lotteries["1"]));

PS: If you want to write it in a fancy way:

 class LotteryCollection extends Map {
   constructor(){
      super();
   }
   //A way to add an element to one lottery
   add(lottery, data){
     if(!this.has(lottery)) this.set(lottery, []);
     this.get(lottery).push({data});
     return this;
   }
 }

 //Create a new instance
 const lotteries = new LotteryCollection();
 //Add data to it
 lotteries
    .add("1", {what:"ever"})
    .add("1", {sth:"else"})
    .add("something", {el:"se"});

 console.log(lotteries.get("1"));

Upvotes: 0

asosnovsky
asosnovsky

Reputation: 2235

The notation [] is for making Arrays, {} is for making Objects.

See the following

const data = {}; // Initialize the object
data['1'] = []// Makes data={'1':[]}
data['1'].push({data: 'data'}) // Makes data = {'1':[{data:'data'}]}

OR

const data = []; // Initialize the Array
data.push([]) // Makes data=[[]]
data[0].push({data: 'data'}) // Makes data = [[{data:'data'}]]

Upvotes: 2

Related Questions