Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change property name of objects

Tags:

javascript

An array of about 5 or more javascript objects in this format [{'a':'man', 'age':'35'},{'b':'woman', 'age':'30'}] needs to be converted to [{gender:'man','age':'35'},{gender:'woman','age':'30'}].

What is an efficient way to do it?

edit
Also the input array may be like this where the keys are switched around: [{'a':'man', 'age':'35'},{'age':'30', 'b':'woman'}] where a, b, ... could be anything and the objects in the array could up to 10 objects.

like image 790
Fred J. Avatar asked Dec 18 '22 09:12

Fred J.


1 Answers

You can iterate through original array and map fields you have to fields you need:

var array=[{'a':'man', 'age':'35'},{'b':'woman', 'age':'30'}];
var newArray = array.map(function(item){
   return {
     age: item.age,
     gender: item.a || item.b
   };
});
console.log(newArray);
like image 121
vp_arth Avatar answered Dec 30 '22 00:12

vp_arth