将逗号分隔字符串转换为键值对象 jQuery

Convert comma separate string to Key value object jQuery

我有以下字符串:

var attrs = "FNAME=abraham,LNAME=lincoln,COUNTRY=USA,JOB=PRESIDENT"

并希望使用 jQuery.

将其转换为键值对象,如下所示
attrs = {
        FName:abraham,
        LName:lincoln,
        COUNTRY:USA,
        JOB:PRESIDENT
        }

您可以使用拆分和创建对象,见下文

var attrs = "FNAME=abraham,LNAME=lincoln,COUNTRY=USA,JOB=PRESIDENT";
var values = attrs.split(",");
var obj = {};
for(var i=0; i<values.length; i++) {
    var keyValue = values[i].split("=");
    obj[keyValue[0]] = keyValue[1];
}
console.log(obj);

$(document).ready(function() {

  var attrs = "FNAME=abraham,LNAME=lincoln,COUNTRY=USA,JOB=PRESIDENT"

  var keysValuesArray = attrs.split(',');
  // keysValuesArray = ["FNAME=abraham", "LNAME=lincoln", "COUNTRY=USA", "JOB=PRESIDENT"]

  var attrsObject = {};

  for (var i = keysValuesArray.length - 1; i >= 0; i--) {

    var keyValueArray = keysValuesArray[i].split('=');
    // Ex: keyValueArray = ["JOB", "PRESIDENT"]

    attrsObject[keyValueArray[0]] = keyValueArray[1];

  }

  console.log(attrsObject);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我建议你使用:

  • .split(",") 分隔你的 key=value 个元素,
  • .forEach() 遍历所有元素,.split("=") 分隔键和值。

工作片段:

var attrs = "FNAME=abraham,LNAME=lincoln,COUNTRY=USA,JOB=PRESIDENT";
var keys_vals = attrs.split(",");
var obj = {};
keys_vals.forEach(function(key_val) {
    var [key, val] = key_val.split("=");
    obj[key] = val;
});
console.log(obj);

你甚至可以使用一些解构:

var attrs = "FNAME=abraham,LNAME=lincoln,COUNTRY=USA,JOB=PRESIDENT";
var obj = {};
attrs.split(",").forEach(function(key_val) {
    var [key, val] = key_val.split("=");
    obj[key] = val;
});
console.log(obj);

ES6 风格的答案:)

const attrs = 'FNAME=abraham,LNAME=lincoln,COUNTRY=USA,JOB=PRESIDENT';
var obj = {};
attrs.split(',').forEach((el) => {
    const [key, value] = el.split('=')
    obj[key] = value;
})
console.log(obj);