javascript - 比较 2 个对象时如何优化慢速“for 循环”?
问题描述
我正在尝试比较 2 个对象,看看是否有任何相同的值。我的对象是这样的:
object_a = [
{id: 4, score: 2},
{id: 5, score: 0},
{id: 2, score: 1},
{id: 1, score: 0},
{id: 3, score: 2},
];
object_b = [
{
id: 1,
questions: [
{
id: 1,
choices: [
{id: 2, score: ''},
{id: 3, score: ''},
],
},
{
id: 2,
choices: [
{id: 6, score: ''},
{id: 8, score: ''},
],
},
],
},
];
因此,例如,我需要获取object_a[2]
并将object_a[4]
它们保存在状态变量中,并且我正在使用react native
...
到目前为止,这是我的代码,它按预期工作,但速度很慢,至少需要在1s
我的组件安装时运行此代码......
state = {
theScore: null,
theDescription: '',
checked: null,
};
async getFromStorage() {
try {
let jsonVal = await AsyncStorage.getItem('@answer');
if (jsonVal !== null) {
return JSON.parse(jsonVal);
}
} catch (e) {
}
};
componentDidMount() {
InteractionManager.runAfterInteractions(() => {
const myRoute = this.props;
this.getFromStorage().then(((storeValue) => {
if (storeValue !== null) {
if (storeValue.length > 0) {
for (let i = 0; i < myRoute.choices.length; i++) {
if (storeValue.some(storage => storage.choice_id === myRoute.choices[i].id)) {
this.setState({checked: myRoute.choices[i].id},
function () {});
this.setState({theScore: myRoute.choices[i].score},
function () {});
}
}
for (let i = 0; i < storeValue.length; i++) {
if (myRoute.choices.some(choice => choice.question_id ===
storeValue[i].question_id) &&
storeValue[i].description !== '') {
this.setState({theDescription: storeValue[i].description},
function () {});
}
}
}
}
}));
});
}
因此,正如您所见,我使用了两个for loops
,因为 count 需要不同,而且我曾经some()
检查过 in 中的值是否object_b
存在object_a
。我不知道是否有更好的方法来做到这一点。谢谢你的时间!
解决方案
您可以像下面的代码一样修改您的代码
if (storeValue !== null) {
if (storeValue.length > 0) {
let checked, theScore, theDescription;
for (let i = 0; i < myRoute.choices.length; i++) {
if (storeValue.some(storage => storage.choice_id === myRoute.choices[i].id)) {
checked = myRoute.choices[i].id;
theScore = myRoute.choices[i].score;
}
}
for (let i = 0; i < storeValue.length; i++) {
if (
myRoute.choices.some(choice => choice.question_id === storeValue[i].question_id) &&
storeValue[i].description !== ''
) {
theDescription = storeValue[i].description;
}
}
this.setState({ checked, theScore, theDescription });
}
}
您不应该this.setState
在同一个函数中多次
调用
尝试only once
在函数结束时结束并调用
推荐阅读
- kentico - Kentico CMS - 如何在页脚中添加链接?
- php - 页面重定向到 404
- haskell - Haskell 共享:代码编译时是否确定共享什么?
- sql - 使用 oracle SQL 查找重复项
- c++ - 分段错误(核心转储)但无法弄清楚
- reactjs - 如何在状态中编写每个迭代?
- python - 递归函数执行策略
- javascript - 克隆输入元素并返回所有新输入,以便保存并通过 GET 请求发送
- keras - Keras 在 fit_generator 之后停止,没有错误
- jestjs - 使用 Stenciljs 和 Jest 在 css background-image 中加载测试图像