簡體   English   中英

JavaScript / ES6 — 替換對象數組中的一些鍵,給定鍵 map

[英]JavaScript / ES6 — Replace some keys in an array of objects, given key map

我有一些(可能非常大)這樣的對象數組:

[
 {
  'before1' => val,
  'same' => val,
  'before2' => val
 },
  ...
]

我需要一種有效的方法來僅替換 map 中的一些鍵(即刪除鍵對我不起作用),並且我有一個像這樣的 map:

keyReplacements = {
 'before1' => 'after1',
 'same' => 'same',
 'before2' => 'after2'
}

我知道 map 中不需要same => same ,但將其包含為完整的翻譯模式會很有幫助。

鑒於此鍵映射,用以下結果替換給定對象數組的有效方法是什么?

[
 {
  'after1' => val,
  'same' => val,
  'after2' => val
 },
  ...
]

我嘗試了以下方法:

    static replaceObjectKeys(objectToReplace, keyMap) {
        objectToReplace.map(o =>
        Object.keys(o).map((key) => ({ [keyMap[key] || key]: o[key] })
        ).reduce((objectToReplace, b) => Object.assign({}, objectToReplace, b)))

        return objectToReplace
    }
    

但它只是返回給我相同的 object 沒有任何替換

const newObject = this.replaceObjectKeys(oldObject, keyMap)
console.log("new obj: ", newObject) // this is the same as oldObject
return newObject

這是使用條目的解決方案:

 const arr = [ { 'before1': 1, 'same': 2, 'before2': 3 }, { 'before1': 4, 'same': 5, }, { 'before1': 6, 'before2': 7 }, { 'same': 8, 'before2': 9 }, ]; const keyReplacements = { 'before1': 'after1', 'same': 'same', // this is not necessary 'before2': 'after2' }; const newArr = arr.map(obj => Object.fromEntries(Object.entries(obj).map(([k, v]) => [keyReplacements[k] || k, v])) ); console.log(newArr);

使用 ES6 map()

arrayObj = arrayObj.map(item => {
  return {
    value: item.key1,
    key2: item.key2
  };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM