如何重命名對像數組中對象的所有鍵? (How does one rename all of an object's keys within an array of objects?)


問題描述

如何重命名對像數組中對象的所有鍵? (How does one rename all of an object's keys within an array of objects?)

有沒有辦法更改對像數組中的鍵名?

代碼: 值列表以更改鍵名。

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

參考解法

方法 1:

You can use reduce and Object.entries for the operation.

  1. reduce is to re‑group the property in the object
  2. Object.entries is to retrieve the key and value pairs in the object.
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',
    status:'sample info',
    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)

方法 2:

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

(by thePeculiarCodertcf01Peter Seliger)

參考文件

  1. How does one rename all of an object's keys within an array of objects? (CC BY‑SA 2.5/3.0/4.0)

#mapping #reduce #javascript #TypeScript #arrays






相關問題

Hibernate 單向父/子關係 - delete() 對子表執行更新而不是刪除 (Hibernate Unidirectional Parent/Child relationship - delete() performs update on child table instead of delete)

TIGER shapefile - 使用和解釋 (TIGER shapefiles - using and interpreting)

查找位置的城市和郵政編碼 (Finding City and Zip Code for a Location)

如何使 Vim 插件 NERDTree 的 <CR> 表現得更像 `go`? (How to make Vim plugin NERDTree's <CR> behave more like `go`?)

在 NHibernate 上的多對多關係上添加自定義列 (Add custom columns on many to many relationship on NHibernate)

在大型 .NET 項目中管理 DTO 和映射 (Managing DTOs and mapping in large .NET project)

使用 Fluent NHibernate 進行繼承映射 (Inheritance Mapping with Fluent NHibernate)

Biztalk映射問題,請想法 (Biztalk Mapping Problem, Ideas please)

BizTalk 數據庫查找 functoid 固定條件 (BizTalk Database Lookup functoid fixed condition)

EntityFramework FluentAPI 映射問題 (EntityFramework FluentAPI mapping issue)

將外鍵添加到現有數據庫 (Adding foreign keys to an already existing database)

如何重命名對像數組中對象的所有鍵? (How does one rename all of an object's keys within an array of objects?)







留言討論