1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Javascriptでオブジェクトリテラル(Object)のキーを変更する(ES6)

Posted at

ES6のスプレッド演算子(...)と分割代入を使用すると簡単に実現できることが分かりました。

分割代入時に、
抽出したいキーは直接指定、
それ以外をスプレッド演算子で可変長引数を定義して受け取ります。

変換したいキーがあることを前提にして変換する

const target = {old_key: 'oldkey_value', other1: 'other_value1', other2: 'other_value2'};
const {old_key, ...others} = target;
const keyTransformed = {...others, new_key: old_key};

console.log(keyTransformed);

// 結果
// {
//  other1: 'other_value1',
//  other2: 'other_value2',
//  new_key: 'oldkey_value'
// }


変換したいkeyがあるときだけ変換する

const keyTransformer = (target) => {
  const {old_key, ...others} = target;
  if (old_key) {
    return {...others, new_key: old_key};
  } else {
    return {...others}
  }
}

const target_has_key = {old_key: 'old_value', other1: 'other_value1', other2: 'other_value2'};
const target_has_no_key = {new_key: 'new_key_value', other1: 'other_value1', other2: 'other_value2'};

console.log(keyTransformer(target_has_key));

// 結果
// {
//  other1: 'other_value1',
//  other2: 'other_value2',
//  new_key: 'old_value'
// }

console.log(keyTransformer(target_has_no_key));

// {
//  new_key: 'new_key_value',
//  other1: 'other_value1',
//  other2: 'other_value2'
// }

1
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?