所以,我有一个像这样的“数据库”:
var db = {
cars: [
{brand: 'x', color: 'blue'},
{brand: 'y', color: 'red'}
],
pcs: {
allInOne: [
{brand: 'z', ram: '4gb'},
{brand: 'v', ram: '8gb'}
],
desktop: [
{brand: 'a', ram: '16gb'},
{brand: 'b', ram: '2gb'}
]
}
}
如您所见,可以有子类别。当然,我的“数据库”比那个更重要。但这个概念是一样的。我需要从对象中获取3个随机项,并使用类别存储它们,如果存在则存储子类别,如下所示:
var random = [
{categorie: 'cars', subcategorie: null, product: {...}},
{categorie: 'cars', subcategorie: null, product: {...}},
{categorie: 'pcs', subcategorie: 'desktop', product: {...}}
]
另外,我需要他们不重复。我怎样才能做到这一点?提前谢谢!
答案 0 :(得分:1)
function getRandom(db, num) {
// FIRST: get an array of all the products with their categories and subcategories
var arr = []; // the array
Object.keys(db).forEach(function(k) { // for each key (category) in db
if(db[k] instanceof Array) { // if the category has no subcategories (if it's an array)
db[k].forEach(function(p) { // then for each product p add an entry with the category k, sucategory null, and the product p
arr.push({categorie: k, subcategorie: null, product: p});
});
}
else { // if this caegory has subcategories
Object.keys(db[k]).forEach(function(sk) { // then for each sucategory
db[k][sk].forEach(function(p) { // add the product with category k, subcategory sk, and product p
arr.push({categorie: k, subcategorie: sk, product: p});
})
});
}
});
// SECOND: get num random entries from the array arr
var res = [];
while(arr.length && num) { // while there is products in the array and num is not yet acheived
var index = Math.floor(Math.random() * arr.length); // get a random index
res.push(arr.splice(index, 1)[0]); // remove the item from arr and push it into res (splice returns an array, see the docs)
num--;
}
return res;
}
var db = {cars: [{brand: 'x', color: 'blue'},{brand: 'y', color: 'red'}],pcs: {allInOne: [{brand: 'z', ram: '4gb'},{brand: 'v', ram: '8gb'}],desktop: [{brand: 'a', ram: '16gb'},{brand: 'b', ram: '2gb'}]}};
console.log(getRandom(db, 3));