首页 > 解决方案 > 如何重命名对象数组中对象的所有键?

问题描述

有没有办法更改对象数组中的键名?

代码: 更改键名的值列表。

var keys = {
    id:'identifier',
    facility:'site',
    status:'info',
    date:'days'
};

更改键名的对象数组

var arrayObj = [{
    id:'jr210',
    facility:'earth',
    status:'sample info',
    date:'Feb 29, 2020'
},
{
    id:'tl980',
    facility:'mars',
    status:'sample info',
    date:'Jan 15, 2020'
}]

预期输出:

var newArrayObj = [{
        identifier:'jr210',
        site:'earth',
        info:'sample info',
        days:'Feb 29, 2020'
    },
    {
        identifier:'tl980',
        site:'mars',
        info:'sample info',
        days:'Jan 15, 2020'
    }]

标签: javascriptarraystypescriptmappingreduce

解决方案


This is a mapping task. Like almost every array method map allows a 2nd argument, the thisArg, a context which gets bound to the callback method and thus is accessibly at such a method's apply/call time.

The provided approach implements a callback method remapObjectWithBoundKeys which utilizes its this context as configuration of how to remap each of an object's key. It does so by reduceing the entries of its key-config and creating a new object by iteratively assigning new key-value pairs to it.

const sampleList = [{
  id:'jr210',
  facility:'earth',
  status:'sample info',
  date:'Feb 29, 2020',
}, {
  id:'tl980',
  facility:'mars',
  status:'sample info',
  date:'Jan 15, 2020',
}];

function remapObjectWithBoundKeys(item) {
  const keyConfig = this;
  return Object
    .entries(keyConfig)
    .reduce((obj, [recentKey, currentKey]) => Object.assign(obj, {
      [currentKey]: item[recentKey]
    }), {});
}

console.log(
  sampleList.map(remapObjectWithBoundKeys, {
    id: 'identifier',
    facility: 'site',
    status: 'info',
    date: 'days',
  })
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

The advantage of the implemented method is that it operates independently from a map task. One easily can utilize or re-use it for any kind of object (re)creation ...

function remapObjectWithBoundKeys(item) {
  const keyConfig = this;
  return Object
    .entries(keyConfig)
    .reduce((obj, [recentKey, currentKey]) => Object.assign(obj, {
      [currentKey]: item[recentKey]
    }), {});
}

const planetType = {
  id:'tl980',
  facility:'mars',
  status:'sample info',
  date:'Jan 15, 2020',
};
const recreatePlanetItem = remapObjectWithBoundKeys.bind({
  id: 'identifier',
  facility: 'site',
  status: 'info',
  date: 'days',
});

console.log(
  planetType,
  recreatePlanetItem(planetType)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }


推荐阅读