Javascript将字符串拆分为多个对象属性

时间:2017-07-06 15:20:46

标签: javascript mongodb

我正在开发Shopify应用程序,我需要进入Mongo的部分订单信息将作为一个属性,通过其API包含单个字符串。举个例子:



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




我实际上需要这个字符串在Mongo中看起来像这样:



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分隔,每个实际值前面都有:我真的很感激建议!

1 个答案:

答案 0 :(得分: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) {
	var strParts = str.split(":");
  obj[strParts[0].replace(/\s+/g, '')] = strParts[1];
  return obj;
}, {})

console.log(mongoExDoc);