获取随机的json对象

时间:2015-07-08 17:48:01

标签: javascript jquery

我想获得随机的hotelCode(例如CUNMXSAKU但随机)对象。 是否可以在javaScript或Jquery中随机使用此对象。

我的JSON:

    var simulatedHotelCodes = {
            "CUNMXSAKU" : {
                "roomCodes" : "DEAL, JRST, JPOV, JSSW, PJRS, PJOV, PJSW, RMOV, RMOF, PRES"
            },
            "CUNMXMAYA" : {
                "roomCodes" : "ROAI, FVAI, DXAI, CAAI, SUAI, CABA, SIGA, PRAI, POFA, ROOM, FMVW, DELX, CASA, SUIT, CASI, SIGN, PROF, PROFS"
            },
            "CUNMXDPAV" : {
                "roomCodes" : "GDVW, MRNA, FMLY, DFAM, HNDO, OCVW, DOLP, FMOV, PCDO, HNOC, PCOV, PFOV, ROHO"
            },
            "CUNMXHIDD" : {
                "roomCodes" : "JRST, JRSU, DOME"
            },
            "CUNMXDSAN" : {
                "roomCodes" : "DEAL, DELX, DEXBA, DXOF, DOFB, PROV, PROF, PROB, POFC, HONY, FAMI, PRJS, DEBL, PRDD"
            }
    };

输出:

"CUNMXMAYA" : {
                "roomCodes" : "ROAI, FVAI, DXAI, CAAI, SUAI, CABA, SIGA, PRAI, POFA, ROOM, FMVW, DELX, CASA, SUIT, CASI, SIGN, PROF, PROFS"
            }

"CUNMXHIDD" : {
                "roomCodes" : "JRST, JRSU, DOME"
            }

随机 提前致谢

3 个答案:

答案 0 :(得分:4)

我使用Object.getOwnPropertyNames()来获取所有属性的数组,然后选择一个随机索引。

var simulatedHotelCodes = {
  "CUNMXSAKU" : {
    "roomCodes" : "DEAL, JRST, JPOV, JSSW, PJRS, PJOV, PJSW, RMOV, RMOF, PRES"
  },
  "CUNMXMAYA" : {
    "roomCodes" : "ROAI, FVAI, DXAI, CAAI, SUAI, CABA, SIGA, PRAI, POFA, ROOM, FMVW, DELX, CASA, SUIT, CASI, SIGN, PROF, PROFS"
  },
  "CUNMXDPAV" : {
    "roomCodes" : "GDVW, MRNA, FMLY, DFAM, HNDO, OCVW, DOLP, FMOV, PCDO, HNOC, PCOV, PFOV, ROHO"
  },
  "CUNMXHIDD" : {
    "roomCodes" : "JRST, JRSU, DOME"
  },
  "CUNMXDSAN" : {
    "roomCodes" : "DEAL, DELX, DEXBA, DXOF, DOFB, PROV, PROF, PROB, POFC, HONY, FAMI, PRJS, DEBL, PRDD"
  }
};

var properties = Object.getOwnPropertyNames(simulatedHotelCodes);
var index = Math.floor(Math.random() * properties.length);
var output = {};
output[properties[index]] = simulatedHotelCodes[properties[index]];
console.log(output);

答案 1 :(得分:0)

是的,这是可能的。但是如果将这些对象放在数组中以便通过数组索引访问这些对象会更容易。由于数组索引是一个整数,您可以随机生成该数组索引,然后访问该对象。

答案 2 :(得分:0)

如果您只关心现代浏览器,请查看@ dave的答案更清晰(并且它可能具有更好的性能)。如果您想在此处使用跨浏览器解决方案,可以选择:

// Define amount of json objects
var length = 0;
for (var key in json)
    length++;
// Get random index and iterate until get it
var rnd = Math.floor(Math.random()*length),
    i = 0,
    obj;
for (var key in json) {
    if (i == rnd) {
        obj = {};
        obj[key] = json[key];
        break;
    }
    i++;
}
// obj has the random item

请注意,您需要使用随机选择的密钥来使用obj。你可以改变这个:

obj = {};
obj[key] = json[key];

到此:

obj = json[key];

仅保存随机项值。

http://jsfiddle.net/paska/m2y7gvnp/1/