简体   繁体   中英

Remove an Item From an Array with JavaScript

I had an array with two objects (can be much more). Like the following

var array = [{ 'a':'hello', 'b': 'world' }, { 'a':'new', 'b': 'world' }];

And I had an object with extra values to delete from that array. Ex

var objectInarray = { 'a':'hello', 'b': 'world', 'c': 'extra' }

How I can delete ?

Edited:

I want to delete array's value { 'a':'hello', 'b': 'world' } using objectInarray . Final result will be like the following

 var array = [{ 'a':'new', 'b': 'world' }];

When we had removed unwanted array's value.

I am not sure if I understand your requirement correctly. If there's any change required, do let me know in the comments.

var array = [{ 'a':'hello', 'b': 'world' }, { 'a':'new', 'b': 'world' }];
var objectInarray = { 'a':'hello', 'b': 'world', 'c': 'extra' };

var opArray = [];
for(var i=0; i<array.length; i++){
    var element = array[i];
    var isAllPresent = true;
    for(key in element){
        if(!(objectInarray[key] && objectInarray[key] === element[key] )){
            isAllPresent = false;
            break;
        }
    }
    if(!isAllPresent){
        opArray.push(element);
    }
}

console.log(opArray);

opArray will have remaining items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM