微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在对象数组中重命名对象的所有键?

如何解决如何在对象数组中重命名对象的所有键?

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

代码 更改键名的值列表。

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',date:'Jan 15,2020'
}]

预期输出

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

解决方法

您可以使用 reduceObject.entries 进行操作。

  1. reduce 是重新组合对象中的属性
  2. Object.entries 是检索对象中的键值对。
type KeyForFinalResult = 'identifier'|'site'|'info'| 'days'
type KeyForReferenceKeys = 'id' | 'facility' | 'status' | 'date' 

type TempObjectType = {
    [T in KeyForReferenceKeys | string ]: string
}

type FinalObjectType = {
    [T in KeyForFinalResult | string]: string
}

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


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


const result = arrayObj.reduce((finalResult: FinalObjectType[],elem)=>{
    let temp: FinalObjectType = {} as FinalObjectType

    Object.entries(keys).forEach((entry: string[] )=> {
        //each entry: [[key,value],[key1,value1]...]
        temp[entry[1]] = elem[entry[0]]
    })
    
    finalResult.push(temp)
 
    return finalResult
},[])


console.log(result)
,

这是一个 mapping 任务。与几乎所有数组方法 map allows a 2nd argument,the thisArg 一样,上下文绑定到回调方法,因此可以在此类方法的应用/调用时间访问。

所提供的方法实现了一个回调方法 remapObjectWithBoundKeys,它利用它的 this 上下文作为如何重新映射每个对象的键的配置。它通过reduce 对其键配置的entries 进行assign 并通过迭代Packaging Tool User's Guide 向其enhancement request 向其添加新的键值对来创建新对象来实现。

const sampleList = [{
  id:'jr210',2020',},{
  id:'tl980',}];

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

已实现方法的优点是它独立于 map 任务运行。可以轻松地将其用于任何类型的对象(重新)创建...

function remapObjectWithBoundKeys(item) {
  const keyConfig = this;
  return Object
    .entries(keyConfig)
    .reduce((obj,{});
}

const planetType = {
  id:'tl980',};
const recreatePlanetItem = remapObjectWithBoundKeys.bind({
  id: 'identifier',});

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。