首页 > 解决方案 > 如果 id 与另一个对象 id 相等,则 React 获取第二个对象

问题描述

data如果此 id 与另一个对象的 id 相等,我正在尝试获取第二个对象。

使用下面的代码,我只能获得 ID 而不是整个

data: {
0: {
    id: 1234,
    name: 'Name 1'
},
2: {
    id: 4321,
    name: 'Name 2'
},
3: {
    id: 876,
    name: 'Name 3'
 }
}
instanceID: 4321

constructor(props) {
super(props);

this.state = {
    defaultInstance: 0
}
}

fetch('api)
.then(response => {
console.log('Data fetched', response);

this.setState({
    defaultInstance: [response.data.indexOf(response.data.find((instance) => instance.id ===   response.instanceID))]
});
});

所以,我想要实现的是添加到defaultInstance那个对象

2: {
    id: 4321,
    name: 'Name 2'
},

标签: javascriptreactjs

解决方案


尝试这个 :

defaultInstance: response.data.filter(d=> d.id == response.instanceID)

推荐阅读