gpt4 book ai didi

javascript - 循环遍历包含对象的数组对象

转载 作者:行者123 更新时间:2023-12-02 23:37:49 24 4
gpt4 key购买 nike

有没有一种方法可以让我循环遍历包含对象的数组对象?

我觉得这看起来很奇怪。让我举个例子:

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 数组作为对象的参数。我想知道是否有一种方法可以让我防止该数组中出现重复的对象。

这就是为什么我想循环它们。我用谷歌搜索了这个问题,找到了一些解决方案,例如 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
);
});
}

使用Array​.prototype​.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

请尝试这个示例

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

结果为 true,因为对象 { from: '55:00', to: '12:00', txt: 'hello' } 在当天的对象列表中.

我希望我已经正确解释了您的情况

关于javascript - 循环遍历包含对象的数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56213040/

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