首页 > 解决方案 > 循环遍历包含对象的数组对象

问题描述

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

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

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但我认为它们不适合我的问题。先感谢您。

标签: javascriptarrays

解决方案


对象无效,假设对象如下:

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

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' }在当天的对象列表中。

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


推荐阅读