我试图实现以下数组/对象,
[
1:[{data:data},{data:data}]
]
如何实现这一目标? 我到目前为止,
var data = [];
data['1'] = {data:data}
但这只是覆盖。
答案 0 :(得分:2)
请参阅以下
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'}]]
答案 1 :(得分: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"));