实际上,我有一段代码,它将Obj中的单词分隔开,为每一列创建一个新行(这实际上非常有效),这正是我想要的。但我注意到,在某些情况下,我在同一组中用逗号分隔单词。
例子:"Masaccio,Sandro Botticelli,Leonardo da Vinci“我们这里有三个词。代码从这3个单词生成一个新行。
但如果我有了这个会怎么样?"Masaccio,Sandro Botticelli,Leonardo,da,Vinci“剧本认为我们有5个单词。所以我的问题是:我应该如何创造这样的东西:"Masaccio,Sandro Botticelli,'Leonardo,da,Vinci‘,用这个’引号‘把它当作一个词而不是3个单词。
有什么想法吗?谢谢!!
const Obj = {
"0":"Masaccio, Sandro Botticelli, Leonardo da Vinci",
"1":"Random, Thing, Uploaded",
"2":"String, Second String, Third string",
"3":"Chef, Police, Cat",
"4":"Legen, Jerry, Jack",
};
const Obj3 = [];
var count = Obj[0].split(", ").length;
var countOuter = Object.keys(Obj).length;
for( var i = 0; i < count; i++){
var string = [];
for( var j = 0; j < countOuter; j++){
string.push(Obj[j].split(", ")[i]);
}
Obj3[i] = string;
}
console.log(Obj3);
发布于 2018-08-10 02:33:52
一种可能的方法是为match逗号分隔的单词创建一个正则表达式(不允许引号' ),或者匹配开始的'引号,直到其匹配的结束'为止。
const Obj = {
"0":"Masaccio, Sandro Botticelli, 'Leonardo, da, Vinci'",
"1":"Random, Thing, Uploaded",
"2":"String, Second String, Third string",
"3":"Chef, Police, Cat",
"4":"Legen, Jerry, Jack",
};
const result = Object.values(Obj).reduce((a, str) => {
const items = str.match(/\w[\w\s]+(?=, |$)|'[^']+'/g);
items.forEach((item, i) => {
if (!a[i]) a[i] = [];
a[i].push(item);
});
return a;
}, []);
console.log(result);
https://stackoverflow.com/questions/51778069
复制相似问题