本文介绍了获取随机的json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取随机的hotelCode(例如CUNMXSAKU但随机)对象.是否可以在javaScript或Jquery中随机拥有此对象.

I want to get random hotelCode (for example CUNMXSAKU but randomly) object.Is it possible to have this object randomly in javaScript or 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"
            }

随机预先感谢

推荐答案

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

I'd use Object.getOwnPropertyNames() to get an array of all the properties, then pick a random index.

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

这篇关于获取随机的json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 15:11