6

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'}];
Biffen
  • 6,249
  • 6
  • 28
  • 36
Sen Soeurn
  • 149
  • 1
  • 2
  • 11

5 Answers5

12

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);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • How's that the correct one? They all return same result. – codejockie Mar 22 '18 at 09:26
  • @JohnKennedy Actually I removed my comment. I have mentioned that comment in the context of react. But the OP didn't mentioned anything about react. So I removed my comment. you can the check the link what i am meaning https://stackoverflow.com/questions/40348171/es6-map-an-array-of-objects-to-return-an-array-of-objects-with-new-keys – Suresh Ponnukalai Mar 22 '18 at 09:31
7

Use array.map

data.map(function(d) { return { letter: d.src } })
Ji aSH
  • 3,206
  • 1
  • 10
  • 18
5

The easiest way is to use map method. Check it out the documentation

data.map(function(item) {
    return { letter: item.src };
})
dloeda
  • 1,516
  • 15
  • 23
3

With map you can achieve what you want. Kindly note that map returns a new array and doesn't modify the existing array.

data.map((item) => ({ letter: item.src }));
codejockie
  • 9,020
  • 4
  • 40
  • 46
1
var newData = data.map(a => { "letter": a.src })
codejockie
  • 9,020
  • 4
  • 40
  • 46
John Willson
  • 444
  • 1
  • 3
  • 13