将对象推入某个键下的对象

问题描述 投票:0回答:2

我正在尝试实现以下数组/对象,

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

这将如何实现?我到目前为止,

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

但这只是覆盖。

javascript
2个回答
2
投票

[]用于制作Arrays{}用于制作Objects

请参阅以下内容

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

要么

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

0
投票

如果我找到了你想要将对象推入哈希表中的数组(可以使用javascript中的对象轻松实现)。所以我们首先需要一个对象:

 const lotteries = {};

现在在存储数据之前,我们需要检查相关数组是否存在,如果不存在,我们需要创建它:

 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:如果你想以一种奇特的方式写它:

 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"));
© www.soinside.com 2019 - 2024. All rights reserved.