George George - 5 months ago 8
Javascript Question

remove keys that start with specific letter

If I have this:

var result = [

{ A: '0', b1: '0' },
{ B: '1', b2: '1' },
{ C: '2', b3: '2' }
];


How can I remove the keys that starts with 'b' ? ( and/or the second key/values pair)

So , to have :

result = [

{ A: '0'},
{ B: '1'},
{ C: '2'}
];


and to be able to call like:

result.letters
,

console.log(result.letters) =

"letters" :
{
'A' : '0',
'B' : '1',
'C' : '2',
..}

Answer

try

result = result.map(function(obj){
  Object.keys(obj).forEach(function(key){
    key.indexOf("b") == 0 && delete obj[key];
  });
  return obj;
})

And to call it as result.letters instead of directly as result make the following modification

var letters = result.map(function(obj){
  Object.keys(obj).forEach(function(key){
    key.indexOf("b") == 0 && delete obj[key];
  });
  return obj;
});    
result = { letters: {}};
letters.forEach(function(obj){
  var keyName = Object.keys(obj)[0];
  result.letters[ keyName ] = obj[ keyName ];
});
Comments