Object.fromEntries()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Object.fromEntries()
静的メソッドは、キーと値の組み合わせのリストをオブジェクトに変換します。
試してみましょう
const entries = new Map([
["foo", "bar"],
["baz", 42],
]);
const obj = Object.fromEntries(entries);
console.log(obj);
// Expected output: Object { foo: "bar", baz: 42 }
構文
Object.fromEntries(iterable)
引数
返値
反復可能な項目から作成されたプロパティを持つ新しいオブジェクト。
説明
Object.fromEntries()
メソッドは、キーと値のリストを取り、これらの項目から作成されたプロパティを持つ新しいオブジェクトを返します。 iterable
引数は [Symbol.iterator]()
メソッドを実装しているオブジェクトであることが求められます。このメソッドは 2 つの要素を持った配列風オブジェクトを生成するイテレーターを返します。最初の要素はプロパティキーとして使われる値であり、次の要素はプロパティのキーに関連付けられる値です。
Object.fromEntries()
は Object.entries()
の逆の動作をしますが、 Object.entries()
は文字列キーのプロパティしか返さないのに対し、 Object.fromEntries()
はシンボルキーのプロパティも作成することができます。
メモ: Array.from()
と異なり、 Object.fromEntries()
は this
の値を使用しないので、他のコンストラクターで呼び出してもその型のオブジェクトは作成されません。
例
Map から Object への変換
Array から Object への変換
オブジェクトの変形
Object.fromEntries
、逆のメソッド Object.entries()
、配列操作メソッドを使用して、以下のようにオブジェクトを変形することができます。
const object1 = { a: 1, b: 2, c: 3 };
const object2 = Object.fromEntries(
Object.entries(object1).map(([key, val]) => [key, val * 2]),
);
console.log(object2);
// { a: 2, b: 4, c: 6 }
仕様書
Specification |
---|
ECMAScript® 2025 Language Specification # sec-object.fromentries |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fromEntries |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support