我遇到的问题是API给了一个长字符串,其中包含需要分解为对象的多个项目.以下是字符串的示例:
"Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n"
Run Code Online (Sandbox Code Playgroud)
它\n用于将所有内容分解为多行.该字符串是API发送的较大对象的一个属性.出于某种原因,当我尝试使用.split它的方法(如下面的完整代码)时,我需要使用JSON.stringify以使我的功能甚至开始工作.
这是我的完整代码:
let rawNoteData = order.customer.note;
let data = JSON.stringify(rawNoteData);
let foo = data.split("\n").reduce(function(obj, str, index) {
let strParts = str.split(":");
obj[strParts[0].replace(/\s+/g, '')] = strParts[1];
return obj;
}, {});
console.log(foo);Run Code Online (Sandbox Code Playgroud)
这创建了看起来很疯狂的对象:
{'"Child1FirstName': ' Arabelle\\nChild 1 Gender' }Run Code Online (Sandbox Code Playgroud)
我认为我的功能只适用于第一个实例.我有点不确定如何解决这个问题,并清理所有疯狂的报价等等.
我的目标是将字符串拆分为一个对象,如下所示:
mongoExDoc: {
child1FirstName: "Ali",
child1Gender: "Female",
child1HairColor: "Blonde",
child1HairStyle: "Wavy",
child1SkinTone: "Tan",
child2FirstName: "Morgan",
child2Gender: "Female",
child2HairColor: "Brown",
child2HairStyle: "Ponytail",
child2SkinTone: "Light",
relationship1To2: "Brother",
relationship2To1: "Brother"
}Run Code Online (Sandbox Code Playgroud)
从那里我将把它的属性与插入到MongoDB中的另一个对象相结合.
任何帮助是极大的赞赏!
J. *_*tus 11
如果order.customer.note是你的示例字符串,那么这应该工作:
let data = "Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n";
//let data = JSON.stringify(rawNoteData); <-- Don't do this. order.customer.note is not an object.
let foo = data.split("\n").reduce(function(obj, str, index) {
let strParts = str.split(":");
if (strParts[0] && strParts[1]) { //<-- Make sure the key & value are not undefined
obj[strParts[0].replace(/\s+/g, '')] = strParts[1].trim(); //<-- Get rid of extra spaces at beginning of value strings
}
return obj;
}, {});
console.log(foo);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6147 次 |
| 最近记录: |