2017-02-11 83 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不客氣! –