Javascript将字符串转换为对象?

Javascript将字符串转换为对象?,javascript,json,Javascript,Json,不知道写什么作为标题,但这是我的问题: if(selectedCountry=="India"){ stateArray=[] Object.keys(jsonObj.India).forEach(function(k) { stateArray.push(k) }); } if(selectedCountry=="USA"){ stateArray=[] Object.keys(jsonObj.USA).forEach(func

不知道写什么作为标题,但这是我的问题:

  if(selectedCountry=="India"){
    stateArray=[]
    Object.keys(jsonObj.India).forEach(function(k) {
      stateArray.push(k)
    });
  }

  if(selectedCountry=="USA"){
    stateArray=[]
    Object.keys(jsonObj.USA).forEach(function(k) {
      stateArray.push(k)
    });
  }
  if(selectedCountry=="UK"){
    stateArray=[]
    Object.keys(jsonObj.UK).forEach(function(k) {
      stateArray.push(k)
    });
  }
  if(selectedCountry=="none"){
    stateArray=[]
  }
  for (var i=0; i<stateArray.length; i++){
    var stateOption = new Option(stateArray[i],stateArray[i])
    if (states.length<stateArray.length+1){
      states.appendChild(stateOption);

    }
有什么办法吗?Thx有两个因素:

  • 减少重复;对于所有可能发生的情况,
    stateArray
    以空数组开始,所以声明一次。若国家并没有,那个么它仍然只是一个空数组

  • 要动态引用键/属性,请使用方括号语法而不是点

    stateArray = [];
    if(selectedCountry !== "none")
        Object.keys(jsonObj[selectedCountry]).forEach(function(k) {
            stateArray.push(k)
        });
    

  • 这将是正确的方法。没有理由先创建数组,然后再创建选项。只需在读取对象的关键帧时创建选项

    var geographicalData=getGeoData();
    var countrySelect=document.getElementById('country');
    populateCombo(countrySelect、geographicalData);
    countrySelect.addEventListener('change',函数(e){
    var stateSelect=document.getElementById('state');
    stateSelect.options.length=0;//空值。
    var selectedCountry=e.target.value;
    if(地理数据[所选国家/地区]){
    populateCombo(stateSelect,地理数据[selectedCountry]);
    }
    });
    countrySelect.dispatchEvent(新的CustomEvent('change'));//触发变化。
    函数populateCombo(combo,obj){
    var keys=Object.keys(obj.sort();
    对于(变量i=0;i
    
    
    你想实现什么?
    stateArray=Object.keys(jsonObj[selectedCountry]|{})
    这里绝对不需要使用
    .forEach
    推送
    -所需的数组是
    对象。keys
    我只是把它从问题中带出来,因为它不是问题的焦点,而是如何省略条件和如何引用动态属性。当然,但是,如果可以的话,为什么要使用5行代码(并避免过程中重复的函数回调)?
    stateArray = [];
    if(selectedCountry !== "none")
        Object.keys(jsonObj[selectedCountry]).forEach(function(k) {
            stateArray.push(k)
        });