问题描述
我收到一个具有键和值的基本模式的对象( Object1 ),然后我想在MongoDB中处理并保存输出,使其包含数组对象。本质上是动态的“位置”和“地址”。
请建议我采取任何有效的方法。
const Object1 = {
date:'07-Sep-2020',Address_1_Ftime: 2,Address_1_Rtime: 0,Address_1_Stime: 49,Address_2_Ftime: 12,Address_2_Rtime: 40,Address_2_Stime: 9
Location1Name:'SAV2',Location1Val:30,Location2Name:'LT232',Location2Val:130,}
const Output =
{
date : '07-Sep-2020',Address:
[
{
name:'Address_1',Ftime:2,Rtime:0,Stime:49
},{
name:'Address_2',Ftime:12,Rtime:40,Stime:9
}
],Locations:[
{
text:Location1,name:SAV2,value:30
},{
text:Location1,name:LT232,value:130
}
]
}
解决方法
尝试完成后,请检查以下代码。 并且让我知道您是否不关注那里的内容。
const Object1 = {
date:'07-Sep-2020',Address_1_Ftime: 2,Address_1_Rtime: 0,Address_1_Stime: 49,Address_2_Ftime: 12,Address_2_Rtime: 40,Address_2_Stime: 9,Location1Name:'SAV2',Location1Val:30,Location2Name:'LT232',Location2Val:130,};
// Initialize the output
const Output = {
Address: {},Locations: {}
};
Object.keys(Object1).forEach(key => {
const value = Object1[key];
if (key === 'date') {
Output.date = value;
} else if (key.startsWith('Address')) {
const addressName = key.substr(0,key.length - 6);
const addressFieldKey = key.substr(key.length - 5);
Output.Address[addressName] = Output.Address[addressName] || {};
Output.Address[addressName][addressFieldKey] = value;
} else if (key.startsWith('Location')) {
const fieldKeyLength = key.endsWith('Name') ? 4 : 3;
const locationName = key.substr(0,key.length - fieldKeyLength);
const locationFieldKey = key.substr(key.length - fieldKeyLength);
Output.Locations[locationName] = Output.Locations[locationName] || {};
Output.Locations[locationName][locationFieldKey] = value;
}
});
// At this point,Address and Locations of Output are still objects not array. So you need the following change.
Output.Address = Object.keys(Output.Address).map(key => ({
name: key,...Output.Address[key]
}));
Output.Locations = Object.keys(Output.Locations).map(key => ({
text: key,name: Output.Locations[key].Name,value: Output.Locations[key].Val
}));
console.log(Output);