JavaScript ES2017(ES8) オブジェクト参照 (object.values(), object.entries()使い方のサンプル

環境
Google Chrome 123.0.6312.86(Official Build) (64 ビット)
Windows 10 Pro 64bit

使用例1
Object.values(obj)
ES2017(ES8) で追加された機能で、オブジェクトが持つ、列挙可能なプロパティの値の配列を返します。
サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var obj = {x:123, y:456};
console.log(Object.values(obj));
Object.entries(obj)
var obj = {x:123, y:456}; console.log(Object.values(obj)); Object.entries(obj)
var obj = {x:123, y:456};
console.log(Object.values(obj));
Object.entries(obj)

結果
[123, 456]

使用例2
ES2017(ES8) で追加された機能で、オブジェクトのプロパティに対して、[key, value] の配列を返します。
var obj = {x:123, y:456};
console.log(Object.entries(obj));
Object.fromEntries(obj)

結果
[[“x",123], [“y":456]]

ES2019(ES10) で追加された機能で、[key, value] の配列をオブジェクトに変換します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var obj = Object.fromEntries([["x", 123], ["y", 456]]);
console.log(obj);
Object.getOwnPropertyNames(obj)
var obj = Object.fromEntries([["x", 123], ["y", 456]]); console.log(obj); Object.getOwnPropertyNames(obj)
var obj = Object.fromEntries([["x", 123], ["y", 456]]);
console.log(obj);
Object.getOwnPropertyNames(obj)

結果
{x: 123, y: 456}

指定したオブジェクトの、列挙可能なプロパティ名のリストを返します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var obj = {x: 123, y: 456, z: 300};
var names = Object.getOwnPropertyNames(obj);
console.log(names);
Object.getOwnPropertySymbols(obj)
var obj = {x: 123, y: 456, z: 300}; var names = Object.getOwnPropertyNames(obj); console.log(names); Object.getOwnPropertySymbols(obj)
var obj = {x: 123, y: 456, z: 300};
var names = Object.getOwnPropertyNames(obj);
console.log(names);
Object.getOwnPropertySymbols(obj)

結果
[“x", “y", “z"]

使用例3
指定したオブジェクトの、列挙可能なシンボルのリストを返します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var obj = {}
obj[Symbol('x')] = 123;
obj[Symbol('y')] = 456;
var symbols = Object.getOwnPropertySymbols(obj);
console.log(symbols);
obj.hasOwnProperty(propertyName)
var obj = {} obj[Symbol('x')] = 123; obj[Symbol('y')] = 456; var symbols = Object.getOwnPropertySymbols(obj); console.log(symbols); obj.hasOwnProperty(propertyName)
var obj = {}
obj[Symbol('x')] = 123;
obj[Symbol('y')] = 456;
var symbols = Object.getOwnPropertySymbols(obj);
console.log(symbols);
obj.hasOwnProperty(propertyName)

結果
[Symbol(x), Symbol(y)]

使用例4
オブジェクトが propertyName で指定した名前の属性を、自身のプロパティとして持っているかを調べます。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var obj = { x:123 };
console.log(obj.hasOwnProperty('x'));
Object.hasOwn(obj, propertyName)
var obj = { x:123 }; console.log(obj.hasOwnProperty('x')); Object.hasOwn(obj, propertyName)
var obj = { x:123 };
console.log(obj.hasOwnProperty('x'));
Object.hasOwn(obj, propertyName)

結果
true

IT

Posted by arkgame