将预格式化的字符串转换为数组

时间:2019-01-14 20:10:38

标签: javascript jquery arrays string

如何在javascript中轻松地将此字符串转换为vector?

"'id': '123', 'name': 'Bob', 'revenue': '51.1'"

很多thinks

1 个答案:

答案 0 :(得分:0)

我假设您正在考虑一个JavaScript不支持的关联数组。但是,JavaScript对象几乎可以被视为关联数组,因为对象实际上只是存储键/值对的存储桶。话虽如此,下面是一些代码,它将解析您的字符串并创建一个对象文字。代码中还有第二个示例,它将每个键/值对作为字符串存储在数组中:

//The original string
var s = "'id': '123', 'name': 'Bob', 'revenue': '51.1'";

//Turn the string into a structured object
var f = s.split(',').map(s => {
  var kv = s.split(':');
  var k = kv[0].trim();
  var v = kv[1].trim();
  return {
    k,
    v
  };
});

//Use reduce to compose into a larger object
var o = f.reduce((accum, el) => {
  var {
    k,
    v
  } = el;
  accum[k.replace(/'/gi, '')] = v;
  return accum;
}, {});
console.log(o);

//Or keep each item as a string in an array
var a = f.reduce((accum, el) => {
  var {
    k,
    v
  } = el;
  accum.push(`${k.replace(/'/gi, '')}:${v}`);
  return accum;
}, []);
console.log(a);