Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to replace key of array in JavaScript? [duplicate]

This is my array:

data = [{"src": 'a'},
        {'src': 'b'},
        {'src': 'c'}];

But I want to change key like this:

data = [{"letter": 'a'},
        {'letter': 'b'},
        {'letter': 'c'}];
like image 785
Sen Soeurn Avatar asked Mar 22 '18 09:03

Sen Soeurn


1 Answers

Use map

var output = data.map( s => ({letter:s.src}) );

Demo

var data = [{
    "src": 'a'
  },
  {
    'src': 'b'
  },
  {
    'src': 'c'
  }
];

console.log(data.map(s => ({
  letter: s.src
})));

But if there are multiple other keys and you only want to change src from it then

var output = data.map( s => {
  if ( s.hasOwnProperty("src") )
  {
     s.letter = s.src;
     delete s.src;   
  }
  return s;
})

Demo

var data = [{
    "src": 'a'
  },
  {
    'src': 'b'
  },
  {
    'src2': 'c'
  }
];

var output = data.map(s => {
  if (s.hasOwnProperty("src")) {
    s.letter = s.src;
    delete s.src;
  }
  return s;
})

console.log(output);
like image 194
gurvinder372 Avatar answered Sep 30 '22 20:09

gurvinder372