【问题标题】:Converting Map<String,String> into array in jquery将 Map<String,String> 转换为 jquery 中的数组
【发布时间】:2017-04-14 09:38:25
【问题描述】:

我在 java 中有这样的地图:

"{one=Print, two=Email, three=Download, four=Send to Cloud}";

我需要在jquery中将上面的字符串转换为数组并循环数组并获取相应的键和值

【问题讨论】:

标签: javascript jquery json dictionary


【解决方案1】:

使用 String#sliceString#trimArray#forEachString#split 方法。

var str = "{one=Print, two=Email, three=Download, four=Send to Cloud}";

str
// remove the space at start and end
  .trim()
  // get string without `{` and `}`
  .slice(1, -1)
  // split by `,`
  .split(',')
  // iterate over the array
  .forEach(function(v) {
    // split by `=`
    var val = v.trim().split('=');
    console.log('key : ' + val[0] + ", value : " + val[1])
  })

更新:如果要生成对象,请使用Array#reduce 方法。

var str = "{one=Print, two=Email, three=Download, four=Send to Cloud}";

var res = str
  .trim()
  .slice(1, -1)
  .split(',')
  .reduce(function(obj, v) {
    var val = v.trim().split('=');
    // define object property
    obj[val[0]] = val[1];
    // return object reference
    return obj;
    // set initial parameter as empty object
  }, {})

console.log(res)

【讨论】:

【解决方案2】:

这是一个简单的技巧:

let arr = jsons.replace('{','').replace('}','').split(',')
arr.map((each)=>{let newVal = each.split('='); return {key: newVal[0], value: newVal[1]}})

【讨论】:

    【解决方案3】:

    试试这个:

    function convertString(string) {
      return string.split(', ').map(function(a) {
        var kvArr = a.split('=');
        return {key: kvArr[0], value: kvArr[1]};
      };
    }
    

    function convertString(string) {
          string = string.slice(1, string.length - 1);
          return string.split(', ').map(function(a) {
            var kvArr = a.split('=');
            return {key: kvArr[0], value: kvArr[1]};
          });
    }
    
    alert(JSON.stringify(convertString("{one=Print, two=Email, three=Download, four=Send to Cloud}")));

    【讨论】:

      猜你喜欢
      • 2016-07-29
      • 2013-05-24
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 2015-11-21
      • 2021-07-04
      相关资源
      最近更新 更多