JavaScriptのObject.valuesとObject.entries
提供:Dev Guides
ES2017(ES8)では、Objectコンストラクターは2つの新しい便利なメソッドObject.valuesとObject.entriesを取得します。 それらの使用法をすぐに調べてみましょう。
Object.values
Object.values はオブジェクトを受け取り、for…inループが与えるのと同じ順序で値を含む配列を返します。 例えば:
const myObj = { piggy: '🐷', birdy: '🐦', bunny: '🐰' }; const myValues = Object.values(myObj); // ["🐷", "🐦", "🐰"]
Object.values はプロトタイプチェーンに従わず、提供されたオブジェクトに直接存在する値を反復処理するだけです。 次の例に示すように、列挙できない値も返されません。
const myObj = { piggy: '🐷', birdy: '🐦', bunny: '🐰' }; Object.defineProperty(myObj, 'koala', { value: '🐨', writable: true, configurable: true, enumerable: true }); let myValues = Object.values(myObj); // ["🐷", "🐦", "🐰", "🐨"] Object.defineProperty(myObj, 'koala', { value: '🐨', writable: true, configurable: true, enumerable: false }); myValues = Object.values(myObj); // ["🐷", "🐦", "🐰"]
Object.entries
前のメソッドと非常によく似ており、Object.entriesはキーと値のペアの配列を含む配列を返します。
const moreAnimals = { camel: '🐫', boar: '🐗', turkey: '🦃' }; const entries = Object.entries(moreAnimals); // [['camel','🐫'],['boar','🐗'],['turkey','🦃']]
新しいmapオブジェクトタイプは、 Object.entries が提供する形状の配列を使用して初期化できるため、物体:
const moreAnimals = { camel: '🐫', boar: '🐗', turkey: '🦃' }; const animalsMap = new Map(Object.entries(moreAnimals)); console.log(animalsMap.size); // 3 console.log(animalsMap.has('turkey')); // true console.log(animalsMap.get('camel')); // '🐫'