最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change property name of objects - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Feb 5, 2017 at 21:18 Fred J. asked Feb 5, 2017 at 21:06 Fred J.Fred J. 6,03913 gold badges60 silver badges112 bronze badges 6
  • Is it always a and b or do you have to check the value ? – adeneo Commented Feb 5, 2017 at 21:07
  • Efficient pared to what? What are you doing right now that you perceive to be insufficient? – user1106925 Commented Feb 5, 2017 at 21:10
  • What's wrong with @NinaScholz answer then? – vp_arth Commented Feb 5, 2017 at 21:21
  • So a and b could be anything, but are there other properties than age in those objects, and if so, how do you propose we'd filter them out ? – adeneo Commented Feb 5, 2017 at 21:22
  • @adeneo No, there is no other property than age. – Fred J. Commented Feb 5, 2017 at 21:23
 |  Show 1 more ment

4 Answers 4

Reset to default 7

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

You could iterate the array and iterate the keys and change only the unknown key to gender.

var data = [{ a: 'man', age: '35' }, { b: 'woman', age: '30' }];

data.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        if (k !== 'age') {
            o.gender = o[k];
            delete o[k];
        }
    });
});

console.log(data);

You should use map method which accepts as parameter a callback function.

Also, you have to use Object.keys(item)[0] in order to get the first key.

var array=[{'a':'man', 'age':'35'},{'b':'woman', 'age':'30'}];
console.log(array.map(function(item){
      return {gender: item[Object.keys(item)[0]],age:item.age};
}));

Like others have e up with suggestions, this is how I would do it:

I would map the keys, to the correct keys a|b => gender, age => age Or define a function, which should give me the right key, based on the value (or type)..

Simple Mapping

const keysMap = {
  gender: ['a', 'b'],
  age: 'age'
};

// get it once.
const rightKeys = Object.keys(keysMap);
const rightKeysLen = rightKeys.length;

function getRightKeyBy(key) {
  for (let i = 0; i < rightKeysLen; i++ ) {
    const condition = keysMap[rightKeys[i]];
    if (key === condition || 
      (condition instanceof Array && condition.indexOf(key) > -1)) {
      return rightKeys[i]
    }
  }
  // if no better key was found return the initial key
  return key;      
}

function convertKeys(obj) {
   const newObj = {};
   Object.keys(obj).forEach(key => {
     newObj[getRightKeyBy(key)] = obj[key];
   });

   return newObj;
}


var array = [{a: 'men', age: '25'},{b: 'woman', age: '35'}];
var correctArray = array.map(convertKeys);

console.log(correctArray);
发布评论

评论列表(0)

  1. 暂无评论