简体   繁体   中英

function to remove object properties from an array of objects

In JS;

Trying to write a function that takes in an array of objects and a series of arguments. The function will remove any properties not given as arguments.

example: input cleanseData([{a: 'b', c:'d'}, {a: 'q'}], 'a');

output [{a: 'b'}, {a: 'q'}]

Here is the function that tried but the objects remain unchanged.

var cleanseData = function(listObj, key1, key2, key3) {
    for (var i=0; i<listObj.length; i++) {
        for(k in listObj[i]) {
            if(k !== key1 && k!==key2 && k!==key3) {
            delete listObj[i].k;
            }
        }
    }
    return listObj;
}

In this line...

delete listObj[i].k;

It's trying to delete a property k , which doesn't exist. Change to...

delete listObj[i][k];

Fiddle

var cleanseData = function (listObj,key) {
    for (var i = 0;i < listObj.length; i++) {
        for(var k in listObj[i])
        if (k!=key) {
            delete listObj[i][k];
        }
    }
    return listObj;
}
console.log(JSON.stringify(cleanseData([{a: 'b', c:'d'}, {a: 'q'}], 'a')));

DEMO

As a matter of style, you could do something like this

function cleanse(arr, proplist) {
  return arr.map(function(elem) {
     var props = Object.keys(elem);
     var props_to_remove = props.filter(function(p) {
      return proplist.indexOf(p) === -1;
     }); 
     props_to_remove.forEach(function(p) {
         delete elem[p];
     })
     return elem;
    });
}    

Note that this returns a new array which satisfies your condition and does not modify the old array you passed in.

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