2017-02-11 99 views
2

所以,我有一个“数据库”是这样的:获取从嵌套对象10个随机项目不重复

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级随机的物品,并将它们存储与categorie,如果它存在subcategorie,就像这样:

var random = [ 
    {categorie: 'cars', subcategorie: null, product: {...}}, 
    {categorie: 'cars', subcategorie: null, product: {...}}, 
    {categorie: 'pcs', subcategorie: 'desktop', product: {...}} 
] 

另外,我需要他们不重复。我怎样才能做到这一点?提前致谢!

+0

你给的例子似乎重复 '汽车' 类别! – rasmeister

+0

@rasmeister是的,分类可以重复,但不是产品 –

+0

我的建议是首先创建一个完整的扁平化阵列,然后很容易洗牌和拼接 – charlietfl

回答

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));

+0

一个该死的天才!谢谢! –

+0

@PeterZelak不客气! –