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'}]; 
0

5 Answers 5

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);

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

2 Comments

How's that the correct one? They all return same result.
@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 stackoverflow.com/questions/40348171/…
7

Use array.map

data.map(function(d) { return { letter: d.src } }) 

Comments

6

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

data.map(function(item) { return { letter: item.src }; }) 

Comments

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 })); 

Comments

1
var newData = data.map(a => { "letter": a.src }) 

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.