gpt4 book ai didi

javascript - 如何使用多个分隔符将字符串减少为自定义对象,Uncaught( promise ): TypeError: Cannot read property of undefined

转载 作者:行者123 更新时间:2023-11-28 14:24:04 25 4
gpt4 key购买 nike

我有一个以下格式的字符串...

“6:00AM - 起床,整理床铺,刷牙。6:45AM - 洗澡。7:15AM - 吃早餐,去上学。”

我想根据句点、逗号和破折号来减少该字符串。基本上通过时间和事件获得一个物体。该对象应该看起来像这样...

{
6:00AM: ['Get up', 'Make the bed', 'Brush my teeth'],
6:45AM: ['Take a shower'],
7:15AM: ['Have breakfast', 'Leave for school']
}

我该如何去做呢?我不太明白。

以下内容是我添加的内容。

现在,我有一个来自数据库的对象,如下所示......

[
{
"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."
}
]

我想循环该数组并用转换后的字符串(即返回的对象)替换每个 activities 属性的值。因此,我创建了一个名为 activities 的单独变量,并将其实例化为一个数组,我希望在其中存储从转换事件 property 返回的对象。所以..

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

我希望实现这样的目标......

[
{
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']
}
]

但是,我收到错误...

Uncaught (in promise): TypeError: Cannot create property '6:00AM' on string '6:00AM - Get up, Make the bed, Brush my teeth.'

我怎样才能让它发挥作用?

最佳答案

这将只使用应在任何最新版本的 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());
}
}

最后的 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' ] }

关于javascript - 如何使用多个分隔符将字符串减少为自定义对象,Uncaught( promise ): TypeError: Cannot read property of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54227980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com