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

时间:2018-08-16 12:56:44

标签: jquery arrays json key-value key-value-store

我有以下字符串:

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

,并希望使用jQuery将其转换为键值对象,如下所示。

attrs = {
        FName:abraham,
        LName:lincoln,
        COUNTRY:USA,
        JOB:PRESIDENT
        }

4 个答案:

答案 0 :(得分:3)

您可以使用split和create对象,请参见下文

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

答案 1 :(得分:1)

$(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>

答案 2 :(得分:1)

我建议您使用:

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

答案 3 :(得分:0)

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