javascript - 循环遍历包含对象的数组对象
问题描述
有没有一种方法可以让我遍历包含对象的数组对象?
我觉得这看起来很奇怪。让我给你举个例子:
data {
monday = [
{from:"55:00", to:"12:00", txt: "hello"},
{from:"55:00", to:"12:00", txt: "study"},
{from:"55:00", to:"12:00", txt: "play"}
],
tuesday = [
{from:"7:00", to:"11:00", txt: "watch"},
{from:"09:00", to:"13:00", txt: "swim"},
]
}
假设用户从一个选择选项中选择了一天,那一天将决定将用户输入的数据保存在数据对象的哪个数组中。
有没有办法让我防止重复的对象被保存在数据对象数组中?
我不知道为什么我觉得还不清楚,但这里有另一个例子:如果用户选择了monday
一天,他将要输入的输入将monday
作为对象的参数保存在数组中。我想知道是否有一种方法可以让我防止该数组中的重复对象。
这就是为什么我想遍历它们。我用谷歌搜索了这个问题,我找到了一些解决方案,for..in
但我认为它们不适合我的问题。先感谢您。
解决方案
对象无效,假设对象如下:
const data = {
monday: [
{ from: '55:00', to: '12:00', txt: 'hello' },
{ from: '09:00', to: '13:00', txt: 'study' },
{ from: '55:00', to: '12:00', txt: 'play' }
],
tuesday: [
{ from: '7:00', to: '11:00', txt: 'watch' },
{ from: '09:00', to: '13:00', txt: 'swim' }
]
};
你可以试试这个验证功能
function hasObject({ day, object }) {
const dataset = data[day];
return dataset.some(data => {
return (
data.from === object.from &&
data.to === object.to &&
data.txt === object.txt
);
});
}
some() 方法测试数组中的至少一个元素是否通过了提供的函数实现的测试。它返回一个布尔值。
请试试这个例子
const data = {
monday: [
{ from: '55:00', to: '12:00', txt: 'hello' },
{ from: '09:00', to: '13:00', txt: 'study' },
{ from: '55:00', to: '12:00', txt: 'play' }
],
tuesday: [
{ from: '7:00', to: '11:00', txt: 'watch' },
{ from: '09:00', to: '13:00', txt: 'swim' }
]
};
function hasObject({ day, object }) {
const dataset = data[day];
return dataset.some(entry => {
return (
entry.from === object.from &&
entry.to === object.to &&
entry.txt === object.txt
);
});
}
const result = hasObject({
day: 'monday',
object: { from: '55:00', to: '12:00', txt: 'hello' }
});
console.log(result);
结果为真,因为该对象{ from: '55:00', to: '12:00', txt: 'hello' }
在当天的对象列表中。
我希望我已经正确解释了你的情况
推荐阅读
- java - 将 LinkedHashMap 转换为 Object
- javascript - 将分钟(字符串)转换为 ISO 8601 持续时间格式
- c# - 将 Unity NetworkMatch 与 UI 相结合
- angular - HTML5 拖放在 Angular 6 上无法按预期工作
- octave - 如何强制在 Octave 中始终绘制实线图
- python - 如何使用页面中存在的警报框截取屏幕截图 [selenium python]
- deployment - Hyperledger Fabric 1.2 版多主机部署
- ios - 如何分别使用 Alamofire 发送参数和正文?
- reactjs - 我需要将我的 Apollo 客户端缓存设置为默认值
- python - 如何使用比较语句在 python 中进行 REST 查询?