[英]Renaming object keys in JS
我想根據另一個對象中定義的映射來重命名對象的某些鍵。 我有這樣的代碼段,但這似乎不起作用,這意味着不重命名對象鍵:
const test = { id: 5, text: 'Plain text', time_created: new Date(), }; const replacements = { id: 'userId', time_created: 'postedAt', }; console.log(test); function renameObjectKeys(obj, replacements) { Object.entries(obj, ([key, _]) => { if (key in Object.keys(replacements)) { if (key !== replacements[key]) { Object.defineProperty(obj, replacements[key], Object.getOwnPropertyDescriptor(obj, key)); delete obj[key]; } } }); } renameObjectKeys(test, replacements); console.log(test);
我怎樣才能實現自己想要的?
我在您的代碼中檢測到兩個問題:
在Object.entries
行中,您正在嘗試執行forEach
類的操作,為整個函數提供謂詞,而Object.entries
不支持您的用例。 因此,您應該使用Array#forEach
。
在該行if (key in Object.keys(replacements))
你誤解in
:這個操作符的對象,以確定是否一個屬性是整個原型鏈中自己的對象或其他地方的一部分。 因此,你應該使用in
上replacements
直接。
const test = { id: 5, text: 'Plain text', time_created: new Date(), }; const replacements = { id: 'userId', time_created: 'postedAt', }; console.log(test); function renameObjectKeys(obj, replacements) { Object.entries(obj).forEach(([key, _]) => { // <---- (1) if (key in replacements) { // <---- (2) if (key !== replacements[key]) { Object.defineProperty(obj, replacements[key], Object.getOwnPropertyDescriptor(obj, key)); delete obj[key]; } } }); } renameObjectKeys(test, replacements); console.log(test);
有一種更簡單的方法,該方法不涉及在適當位置重命名這些屬性,而是在不更改輸入對象的情況下創建新對象:
const test = { id: 5, text: 'Plain text', time_created: new Date(), } const replaces = { id: 'userId', time_created: 'postedAt', } // Converts entries to an object back again const fromEntries = entries => entries.reduce ((o, [key, value]) => ({ ...o, [key]: value }), {}) const renameProps = (replaces, obj) => fromEntries ( Object.entries (obj) .map (([key, value]) => [ replaces.hasOwnProperty (key) ? replaces[key] : key, value ]) ) const renamed = renameProps (replaces, test) console.log ('from ', test) console.log ('to ', renamed)
嘗試這個,
const test = {
id: 5,
text: 'Plain text',
time_created: new Date(),
};
const replacements = {
id: 'userId',
time_created: 'postedAt',
};
console.log("test",test);
function renameObjectKeys(obj, replacements) {
for (var key in replacements)
{
var temp = test[key];
delete test[key];
test[replacements[key]] = temp;
}
}
renameObjectKeys(test, replacements);
console.log("test",test);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.