【发布时间】:2018-05-15 01:58:29
【问题描述】:
我有一个对象数组,其中一些对象有一个属性,其中包含逗号。我想要做的是,如果该对象具有包含逗号的属性,我想将其拆分为一个新对象并将所有其他属性递归复制到一个新的数组元素中。
示例: 我需要转换这个对象数组:
[ {
prop1: ' text1 , text2 , text3 ',
prop2: 'stuff1',
prop3: 'stuff1',
prop4: 'stuff1',
prop5: 'https://www.stuff1.com' },
{
prop1: ' text1 , text2 , text3 ',
prop2: 'stuff2',
prop3: 'stuff2',
prop4: 'stuff2',
prop5: 'https://www.awefewfew.com' },
]
到这里:
[ {
prop1: 'text1',
prop2: 'stuff1',
prop3: 'stuff1',
prop4: 'stuff1',
prop5: 'https://www.stuff1.com' },
{
prop1: 'text2',
prop2: 'stuff1',
prop3: 'stuff1',
prop4: 'stuff1',
prop5: 'https://www.stuff1.com' },
{
prop1: 'text3 ',
prop2: 'stuff1',
prop3: 'stuff1',
prop4: 'stuff1',
prop5: 'https://www.stuff1.com' },
{
prop1: 'text1',
prop2: 'stuff2',
prop3: 'stuff2',
prop4: 'stuff2',
prop5: 'https://www.awefewfew.com' },
{
prop1: 'text2',
prop2: 'stuff2',
prop3: 'stuff2',
prop4: 'stuff2',
prop5: 'https://www.awefewfew.com' },
{
prop1: 'text3',
prop2: 'stuff2',
prop3: 'stuff2',
prop4: 'stuff2',
prop5: 'https://www.awefewfew.com' },
]
通过在 prop1 处拆分,然后递归地将所有其他属性复制到新的数组元素中。
编辑: 我实际上可以在 google 表格中找到它,但不能完全将它移植到 vanilla JS:
function splitColumnAndRepeatRows(anArray, splitColumnIndex) {
var output = [];
for (i in anArray){
var splitArray = anArray[i][splitColumnIndex].split(",");
for (j in splitArray){
var row = anArray[i].slice(0);
row[splitColumnIndex] = alltrim(splitArray[j]);
output.push(row);
}
}
return output;
}
function alltrim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
【问题讨论】:
-
到目前为止你有没有尝试过? StackOverflow 不是免费的代码编写服务,希望您能try to solve your own problem first。请更新您的问题以显示您已经尝试过的内容,并在minimal, complete, and verifiable example 中显示您面临的具体问题。欲了解更多信息,请参阅how to ask a good question,并拨打tour of the site
-
@Maxinef23 我添加了答案,希望它能按照您的期望工作。谢谢
-
@JaromandaX 公平点。添加了我想出的内容。
标签: javascript arrays json parsing split