解析字符串以创建一个对象数组,javascript

Parsing through string to create an array of objects, javascript

本文关键字:数组 javascript 一个对象 创建 字符串      更新时间:2023-09-26

我返回一个包含字符串的对象数组。每当字符串有管道时,我想解析该字符串并创建一个新对象。

下面是阵列的一个例子

[
    {
        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循环来遍历它,并获取数据[I].list.synonyms,但这会返回一个字符串,如"和平条约|和平条约|协定|协定"

我如何解析并将所有5个同义词放入它们自己的对象中?

非常感谢

使用data[i].list.neysons.split("|")。它将返回一个字符串数组,该数组由您传递给它的任何字符分隔。

您可以使用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>"