【发布时间】:2021-07-10 17:42:54
【问题描述】:
我正在尝试比较 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,因为计数需要不同,而且我使用some() 来检查object_b 中的值是否存在于object_a 中。我不知道是否有更好的方法来做到这一点。感谢您的宝贵时间!
【问题讨论】:
标签: javascript arrays reactjs react-native object