我正在返回一个包含字符串的对象数组。我想解析字符串并在字符串有管道时创建一个新对象。
以下是数组
的示例[
{
list : {
category : '(noun)',
synonyms : 'order|war (antonym)'
}
}, {
list : {
category : '(noun)',
synonyms : 'harmony|concord|concordance'
}
}, {
list : {
category : '(noun)',
synonyms : 'peacefulness|peace of mind|repose|serenity|heartsease|ataraxis|tranquillity|tranquility|quietness|quietude'
}
}, {
list : {
category : '(noun)',
synonyms : 'public security|security'
}
}, {
list : {
category : '(noun)',
synonyms : 'peace treaty|pacification|treaty|pact|accord'
}
}
]
我循环使用for循环并获取data [i] .list.synonyms,但这会返回一个字符串,如'peace treaty | pacification | treaty | pact | accord'
我如何解析这个并将所有5个同义词放入他们自己的对象中?
非常感谢
答案 0 :(得分:0)
使用data[i].list.synonyms.split("|")。它将返回由您传递给它的任何字符分隔的字符串数组。
答案 1 :(得分:0)
您可以使用String.prototype.split
。
例如,此代码段修改您的对象,使其现在包含一个同义词数组:
// Your object:
var obj = [
{ list : { category : '(noun)', synonyms : 'order|war (antonym)' } },
{ list : { category : '(noun)', synonyms : 'harmony|concord|concordance' } },
{ list : { category : '(noun)', synonyms : 'peacefulness|peace of mind|repose|serenity|heartsease|ataraxis|tranquillity|tranquility|quietness|quietude' } },
{ list : { category : '(noun)', synonyms : 'public security|security' } },
{ list : { category : '(noun)', synonyms : 'peace treaty|pacification|treaty|pact|accord' } }
];
// Modification
obj.forEach(function(x) {
x.list.synonyms = x.list.synonyms.split('|');
});
// Demonstration purposes only:
document.body.innerHTML = "<pre>" + JSON.stringify(obj, null, 4) + "</pre>"