将字符串拆分为对象javascript

时间:2017-03-07 16:03:57

标签: javascript node.js

我有这个字符串。

'"pen pineapple" apple pen "pen pen"'

有没有一种好方法可以将其转换为如下所示的对象:

{
a: "pen pineapple",
b: "apple",
c: "pen",
d: "pen pen"
}

我正在寻找纯javascript的解决方案!

4 个答案:

答案 0 :(得分:1)

拆分带引号的字符串......

https://stackoverflow.com/a/18647776/2725684

然后将该数组转换为对象......

https://stackoverflow.com/a/4215753/2725684

所以,当你把这些答案结合起来时,它看起来像这样......

var myRegexp = /[^\s"]+|"([^"]*)"/gi;
var myString = '"pen pineapple" apple pen "pen pen"';
var myArray = [];

do {
    var match = myRegexp.exec(myString);
    if (match != null) {
        myArray.push(match[1] ? match[1] : match[0]);
    }
} while (match != null);

var obj = myArray.reduce(function(acc, cur, i) {
  acc[i] = cur;
  return acc;
}, {});

console.log(obj);

答案 1 :(得分:1)

您可以使用Split a string by commas but ignore commas within double-quotes using Javascript的改编版本并使用Number#toString方法获取密钥。

var str = '"pen pineapple" apple pen "pen pen"',
    arr = str.match(/(".*?"|[^" \s]+)(?=\s* |\s*$)/g),
    object = {};

arr.forEach(function (a, i) {
    object[(i + 10).toString(36)] = a.replace(/"/g, '');
})    

console.log(object);

答案 2 :(得分:0)

这可能不是最有效的功能,但可以满足您的需要(返回数组)

function splitter(inputString) {
    var splitted = inputString.split(' ');
    var out = []
    var temp = "";
    var quoteStarted = false;

    for (i = 0; i < splitted.length; i++) {

        if (splitted[i].indexOf('"') > -1 && !quoteStarted) {
            temp += splitted[i] + " ";
            quoteStarted = true;
        } else if (quoteStarted && splitted[i].indexOf('"') == -1) {
            temp += splitted[i] + " ";
        } else if (quoteStarted && splitted[i].indexOf('"') > -1) {
            temp += splitted[i];
            out.push(temp);
            quoteStarted = false;
            temp = "";
        } else {
            out.push(splitted[i])
        }
    }
    return out;
}

答案 3 :(得分:0)

可以像这样用纯JavaScript实现

let str = '"pen pineapple" "apple" "pen" "pen pen"'
let obj = {}
let pattern = /".*?"/g;
let index = ["a","b","c","d","e"]
let i=0
let key

while(current = pattern.exec(str))
 {
   key = index[i]
   obj[key] = current[0].replace('"','')
   i++
 }

console.log(obj)