如何使用字符串生成数组?

时间:2017-12-10 06:01:04

标签: javascript arrays string list dictionary

我有一个这种格式的长字符串:

A from $37
B from $46
D from $70
P from $61
S from $40

这是预期的结果:

 [{A:$37},{B:$46},{D:$70},{P:$61},{S:$40}]

如何从字符串创建此输出?

3 个答案:

答案 0 :(得分:1)

var strings = ['A from $37','B from $46','D from $70','P from $61','S from $40'];

var outputArr = [];

for(var i = 0 ; i < strings.length;i++){
  var items = strings[i].split(" from ");
  outputArr.push({Key:items[0], Value:items[1]});  
}

console.log(outputArr);

您将无法在JavaScript对象中创建动态密钥,

您可以将其添加为数组中的键值对象

这里是代码段的demo

答案 1 :(得分:1)

使用正则表达式匹配和es6动态对象键

const str = `
A from $37
B from $46
D from $70
P from $61
S from $40`;

const objectMapper = (s) => {
  const arr = s.match(/(^[a-z]+\b)|(\$.+)/gi);
  return {[arr[0]]: arr[1]};
};
const res = str.trim().split('\n').map(objectMapper)


console.log(JSON.stringify(res))

答案 2 :(得分:0)

您可以按\n拆分它们,然后按from

拆分

&#13;
&#13;
var f = `A from $37
B from $46
D from $70
P from $61
S from $40`;
var items = new Array();
f.split('\n').forEach((i) => {
   var j = i.split(' from ');
   var json = '{"'+j[0]+'":"'+j[1]+'"}';
   items.push(JSON.parse(json));
});
console.log(items);
&#13;
&#13;
&#13;