0

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;
}
2
  • Are you getting an error? What error is it? Commented Sep 8, 2014 at 4:02
  • It might be simpler to convert arguments 1 to n to an array called say keys, then you could do something like if (keys.indexOf(k) == -1) {/* delete key */}. But you need a hasOwnProperty test to exclude inherited properties, or use Object.keys. You might also have issues with !== given that keys are always strings and you might provide numbers as arguments. Commented Sep 8, 2014 at 4:05

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1
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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.