[英]How to reduce a string into a custom object using several delimiters, Uncaught (in promise): TypeError: Cannot read property of undefined
I have a string that exists in the following format... 我有一个以下格式的字符串...
"6:00AM - Get up, Make the bed, Brush my teeth. 6:45AM - Take a shower. 7:15AM - Have breakfast, Leave for school." “ 6:00 AM-起床,铺床,刷牙。6:45 AM-洗澡。7:15 AM-吃早餐,上学。”
I'd like to reduce that string based on the period, comma and dash. 我想根据句号,逗号和破折号来减少该字符串。 Basically get an object with time and activities. 基本上得到一个具有时间和活动的对象。 The object should look like this... 对象应该看起来像这样...
{
6:00AM: ['Get up', 'Make the bed', 'Brush my teeth'],
6:45AM: ['Take a shower'],
7:15AM: ['Have breakfast', 'Leave for school']
}
How can I go about doing that? 我该怎么做呢? I can't quite figure it out. 我不太清楚。
The content below is what I've added. 以下是我添加的内容。
Now, I have an object coming from the database that looks like this... 现在,我有一个来自数据库的对象,看起来像这样...
[
{
"id": 1,
"day": "Monday",
"activities": "6:00AM - Get up, Make the bed, Brush my teeth. 6:45AM - Take a shower. 7:15AM - Have breakfast, Leave for school."
},
{
"id": 2,
"day": "Tuesday",
"activities": "6:00AM - Get up, Make the bed, Brush my teeth. 6:45AM - Take a shower. 7:15AM - Have breakfast, Leave for school."
}
]
I'd like to loop over that array and replace the value of each activities
property with the transformed string (ie the returned object). 我想遍历该数组,并用转换后的字符串(即返回的对象)替换每个activities
属性的值。 I have thus created a separate variable called activities and instantiated it to an array, where I wish to store the objects returned from transforming the activities property
. 因此,我创建了一个单独的变量,称为activity,并将其实例化为一个数组,在该数组中我希望存储从转换activity property
返回的对象。 So.. 所以..
let activities = [];
/* My function */
private splitter() {
const activities = this.itinerary.map(item => {
return item.activities;
});
const results = {};
const res = activities.map(str => {
for (const result of str.split('.').map(x => x.trim())) {
if (result) {
const [time, actions] = result.split(' - ');
results[time] = actions.split(',').map(x => x.trim());
}
}
return results;
});
return res;
}
I hoped to achieve something that looks like this... 我希望能达到这样的目标...
[
{
6:00AM: ['Get up', 'Make the bed', 'Brush my teeth'],
6:45AM: ['Take a shower'],
7:15AM: ['Have breakfast', 'Leave for school']
},
{
6:00AM: ['Get up', 'Make the bed', 'Brush my teeth'],
6:45AM: ['Take a shower'],
7:15AM: ['Have breakfast', 'Leave for school']
}
]
However, I get the error... 但是,我得到了错误...
Uncaught (in promise): TypeError: Cannot create property '6:00AM' on string '6:00AM - Get up, Make the bed, Brush my teeth.'
How can I get this to work? 我该如何工作?
This will do the trick using nothing but built-in JavaScript that should run in any recent version of Node.JS: 这将使用仅可在任何最新版本的Node.JS中运行的内置JavaScript来解决问题:
const str = "6:00AM - Get up, Make the bed, Brush my teeth. 6:45AM - Take a shower. 7:15AM - Have breakfast, Leave for school."
sentences = {};
// split the string on periods, and trim each sentence
for (sentence of str.split('.').map(x => x.trim())) {
// you end up with a completely empty sentence when the last
// sentence ends in a period, which is uninteresting
if (sentence) {
// split each sentence on a hyphen, and assume the first
// element is time and the second is actions
let [time, actions] = sentence.split(' - ');
// split the actions string on commas and trim whitespace;
// store that in our sentences object
sentences[time] = actions.split(',').map(x => x.trim());
}
}
Then console.log(sentences)
at the end gives you: 然后最后的console.log(sentences)
为您提供:
{ '6:00AM': [ 'Get up', 'Make the bed', 'Brush my teeth' ],
'6:45AM': [ 'Take a shower' ],
'7:15AM': [ 'Have breakfast', 'Leave for school' ] }
Maybe this is a pretty naive solution, but you can resolve something like this with a combination of split
and map
. 也许这是一个非常幼稚的解决方案,但是您可以结合使用split
和map
来解决类似的问题。
Lets say you have your string. 假设您有字符串。 You can start splitting it by the first biggest delimiter (the period in this example). 您可以开始使用第一个最大的分隔符(在此示例中为句点)对其进行分割。
const string = "6:00AM - Get up, Make the bed, Brush my teeth. 6:45AM - Take a shower. 7:15AM - Have breakfast, Leave for school."
const firstSplit = string.split(".");
What you have now in firstSplit
would be something like ["6:00AM - Get up, Make the bed, Brush my teeth", "6:45AM - Take a shower", "7:15AM - Have breakfast, Leave for school"]
. 您现在在firstSplit
所拥有的内容类似于["6:00AM - Get up, Make the bed, Brush my teeth", "6:45AM - Take a shower", "7:15AM - Have breakfast, Leave for school"]
firstSplit
["6:00AM - Get up, Make the bed, Brush my teeth", "6:45AM - Take a shower", "7:15AM - Have breakfast, Leave for school"]
。 What you can do now is to further split each one of the values in this array into hour and activites. 您现在可以做的是将该数组中的每个值进一步拆分为小时并激活。
Since I want to split each item in the array (obtaining a new array with the results) I will use a map
由于我想拆分数组中的每个项目(使用结果获取一个新数组),因此我将使用一个map
const secondSplit = firstSplit.map(each => each.split(" - "))
Now secondSplit
will look something like [["6:00AM", "Get up, Make the bed, Brush my teeth"], ["6:45AM", "Take a shower"], ["7:15AM", "Have breakfast, Leave for school"]]
现在, secondSplit
看起来像[["6:00AM", "Get up, Make the bed, Brush my teeth"], ["6:45AM", "Take a shower"], ["7:15AM", "Have breakfast, Leave for school"]]
Now lets transform that weird array of arrays into an object in which the first position of each small array is a key, and second a value. 现在,将这个奇怪的数组数组转换为一个对象,其中每个小数组的第一个位置是键,第二个是值。 I will use vainilla javascript but of course this will be easier with any js library out there (like lodash or ramda) 我将使用vainilla javascript,但是当然可以使用任何js库(例如lodash或ramda)来简化
const almostThere = secondSplit.reduce((object, subarray) => {
object[subarray[0]] = subarray[1]
return object
}, {})
This is incredible close to what you actually want. 这真是难以置信,接近您的实际需求。 The object is looking something like: 该对象看起来像:
{
6:00AM: "Get up, Make the bed, Brush my teeth",
6:45AM: "Take a shower",
7:15AM: "Have breakfast, Leave for school"
}
Notice we are missing one more split on each of the object values. 注意,我们在每个对象值上都缺少一个拆分。 We can tackle that by modifying the reduce
done previously 我们可以通过修改以前完成的reduce
来解决
const yeay = secondSplit.reduce((object, subarray) => {
object[subarray[0]] = subarray[1].split(", ")
}, {})
And there you go! 然后你走了!
Altogether it might look something like this: 总共看起来可能像这样:
const firstSplit = string.split(".")
.map(each => each.split(" - "))
.reduce((object, subarray) => {
object[subarray[0]] = subarray[1].split(", ")
return object
}, {})
Which might be optimized to something like this: 可以针对以下内容进行优化:
const yeay = string.split(".")
.reduce((object, hourAndChores) => {
const splittedHourAndChores = hourAndChores.split(" - ");
object[splittedHourAndChores[0]] = splittedHourAndChores[1].split(", ")
return object
}, {})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.