Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

javascript - Remove entire key when matched with matched array values

I am new to react, I have an object and an array, I want to get details of unmatched items from the object when compared with array values. I tried but shows all the data when consol.log. here is my code

var content:[
    0:{id:20, name:'Jack Daniel'}
    1:{id:21, name:'Sophie McDonald'}
    2:{id:22, name:'Jason Thomas'}
    3:{id:23, name:'Chris Williams'}
]

var filter:[Sophie McDonald, Chris Williams]

filterValues = content.filter(item=> {
            
    for(var i = 0;i<filter.length;i++) {
        if (item.name === filtered[i])
        {
            return item              
        }       
     } 
});
console.log(filteredValues)
  // returns  0:{id:21, name:'Sophie McDonald'}
  //          1:{id:23, name:'Chris Williams'}

But I need unmatched results,

filterValues = content.filter(item=> {
            
    for(var i = 0;i<filter.length;i++) {
        if (item.name !== filtered[i])
        {
            return item              
        }       
     } 
});
console.log(filteredValues)
// returns  0:{id:20, name:'Jack Daniel'}
//          1:{id:21, name:'Sophie McDonald'}
//          2:{id:22, name:'Jason Thomas'}
//          3:{id:23, name:'Chris Williams'}

Result must be

 0:{id:20, name:'Jack Daniel'}
 1:{id:22, name:'Jason Thomas'}
question from:https://stackoverflow.com/questions/65926801/remove-entire-key-when-matched-with-matched-array-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try using filter, checking if the values of the array are present in your object values:

const content = [{
    id: 20,
    name: 'Jack Daniel'
  },
  {
    id: 21,
    name: 'Sophie McDonald'
  },
  {
    id: 22,
    name: 'Jason Thomas'
  },
  {
    id: 23,
    name: 'Chris Williams'
  }
];

const values = ['Sophie McDonald', 'Chris Williams'];

const filteredValues = content.filter(({
  name
}) => !values.includes(name));

console.log(filteredValues);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...