2017-07-06 62 views
0

我正在使用Shopify应用程序,并且我需要进入Mongo的部分订单信息将作为通过其API包含单个字符串的属性发布。举个例子:Javascript将字符串拆分为多个对象属性

"note": "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",

我真的需要这个字符串看起来像这样在蒙戈:

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" 
 
}

或者沿着这些路线的东西。属性值本身不会改变。正如你所看到的,每个值由\ n隔开,每个实际值前面都有一个:.我会很感激的建议!

+3

让我们知道您是否尝试过 – sidgate

+0

string.split( '\ n')将得到线。 split('').join('')将删除空格。 +将允许你连接花括号 – danh

回答

3

一览:

var data = {"note": "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"}; 
 

 
var mongoExDoc = data.note.split("\n").reduce(function(obj, str, index) { 
 
\t var strParts = str.split(":"); 
 
    obj[strParts[0].replace(/\s+/g, '')] = strParts[1]; 
 
    return obj; 
 
}, {}) 
 

 
console.log(mongoExDoc);

+0

这似乎真的很接近!我应该提到mongoExDoc是一个由流星方法创建的对象,并且还有来自API其他部分的数据。有没有一种好方法(而不是构建整个对象),只需将每个属性值添加到变量中? – JoethaCoder

+0

你可以使用'Object.assign()'来合并对象:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign – tymeJV

+0

当试图记录它时我得到︰ 异常,同时调用方法'getAllOrders'TypeError:无法读取属性'拆分'为空 但我简单地登录从它的API进来的字符串它的工作。 – JoethaCoder