LoginSignup
1
0

【JavaScript】オブジェクトの複数のキーを変更する方法

Last updated at Posted at 2024-03-08

以下のように記述するとオブジェクトの複数のキーを指定したものに変更できます。

let sample = { name: "Sample", country: "Japan", gender: "male" }

// 変更するプロパティ名のオブジェクトを作成
// 以下の場合には name を firstName に変更する
let newKeys = { name: "firstName" }

function renameKeys(obj, newKeys) {
  // オブジェクトのすべてのキーを取得し、それぞれに対して以下の処理を行う
  const keyValues = Object.keys(obj).map(key => {
    // 新しいキーを取得します。新しいキーが存在しない場合は元のキーを使用
    const newKey = newKeys[key] || key
    // 新しいキーと元の値を持つ新しいオブジェクトを作成
    return { [newKey]: obj[key] }
  })
  // 新しいオブジェクトの配列を1つのオブジェクトにマージ
  return Object.assign({}, ...keyValues)
}

sample = renameKeys(sample, newKeys)

console.log(sample) // {firstName: "Sample", country: "Japan", gender: "male"}
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0