有没有一种方法可以让我遍历包含对象的数组对象?
我觉得这很奇怪。让我举个例子:
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
天,那么他将要输入的输入将保存在{{1}中}数组作为对象的参数。我想知道是否有一种方法可以防止该数组中的对象重复。
这就是为什么我要遍历它们。我在该问题上进行了搜索,发现了诸如monday
之类的解决方案,但我认为它们不适合我的问题。预先谢谢你。
答案 0 :(得分:1)
该对象无效,假定该对象是以下对象:
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);
结果为true,因为对象{ from: '55:00', to: '12:00', txt: 'hello' }
在当天的对象列表中。
希望我能正确解释您的情况
答案 1 :(得分:0)
您可以执行以下操作:
_favOrUnFav = () => {
if (!this.state.fav){
const {
providerId,
providerName,
providerService
} = this.state;
this.ref.set({
providerId,
providerName,
providerService
})
} else ref.set(null) OR you can use ref.remove()
}
如果对象相同,将在其中创建一个比较对象的功能(const {
fav
} = this.state
<Icon
name={`ios-heart${fav ? "" : "-empty"}`}
style={{ backgroundColor: "red" }}
size={30}
color="#fff"
onPress={this._favOrUnFav}
/>
函数-请注意,这是基于用例的 VERY 简单化比较。这只会比较原始对象值等)。另一个函数let 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" }, ] }
let selectedDay = 'monday'
let dubData = { from: "09:00", to: "13:00", txt: "study"}
let cleanData = { from: "19:00", to: "21:00", txt: "FOO"}
let areSame = (o1,o2) => Object.entries(o1).every(([k,v]) => o2[k] === v)
let hasEntry = (arr, obj) => arr.some(x => areSame(obj, x))
console.log(hasEntry(data[selectedDay], dubData))
console.log(hasEntry(data[selectedDay], cleanData))
将检查数组中是否存在重复的对象。
因此,您将仅基于所选日期(在这种情况下为areSame
-如hasEntry
)获得所需的数据集slice
,并将新对象传递给{{1 }}进行验证。