2017-07-06 67 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