我的问题可能没有其他类似的问题那么具有挑战性,但对我来说却差不多。
我有一个对象数组,如果名称匹配,我需要根据名称对字符串数组进行过滤,我想删除名称匹配的对象
如下所示:
nameObjects = [{name: 'name3', value: 'some val'},{name: 'name1', value:'some other val'}]
names = ['name1','name2','name3']
我已经尝试过仅使用for循环进行以下操作,但是我敢肯定有一种更快(且正确的大声笑)过滤器方法可以工作
for(i=0; i < this.names.length; i++){
for(j=0; j < this.nameObjects.length; j++){
if(this.names[i] === this.nameObjects[j].name){
this.files.splice(i,this.nameObjects[j])
}
}
}
也为逻辑不佳而感到遗憾^
答案 0 :(得分:3)
在遍历数组时,请勿更改数组。
您可以简单地将constructor(){
super()
this.state={
userDetails:{},
userDetailsCopy: {}
}
}
componentDidMount(){
// API will return the following data
apiUserDetails : [
{
'name':'Tom',
'age' : '28'
},
{
'name':'Jerry',
'age' : '20'
}
]
resp.data is nothing but apiUserDetails
/////
apiCall()
.then((reps) => {
this.setState({
userDetails: resp.data,
userDetailsCopy: resp.data
})
})
}
updateValue = (text,i) => {
let userDetail = this.state.userDetails
userDetail[i].name = text
this.setState({
userDetails: userDetail
})
}
submit = () => {
console.log(this.state.userDetials) // returns updated values
console.log(this.state.userDetailsCopy) // also return updated values instead of returning old API data
}
Need a quick solution on this.
与Array.prototype.filter
结合使用以获得期望的结果
Array.prototype.includes
答案 1 :(得分:1)
const nameObjects = [
{ name: "name3", value: "some val" },
{ name: "name1", value: "some other val" },
];
const names = ["name1", "name2"];
const result = nameObjects.filter(obj => !names.includes(obj.name));
console.log(result);