Get the number of members using variables for Object Key in JS

Write down this object-related in JS. My notes.

Node.js the result of various investigations by wanting to use Object when data is acquired from DynamoDB in a good way.

Use variables for Object Key

If you specify around th[]e variable that becomes key at the time of object definition, it will do well.

var value = "salad"
var key = "name"
var obj = {[key]: value} // {"name": "salad"}

Reference

JavaScript Primer - 迷わないための入門書
JavaScript Primerは、JavaScriptの基礎から応用までを一貫して学べる入門書です。

Get the number of members in Object

For example, consider a time when there was such an Object.

var userScore = {
 "sato": 100,
  "suzuki": 80,
  "takahashi": 90,
  "tanaka": 85
}

It's the username and the score of that user.

So what do you do when you want to get the number of users who have a score recorded from this object?

Of course, Object does not have a length property.

console .log (userScore.length) // Undefined, of course

Use Object.keys()

Create an array with Object Key as an element and refer to the length property of that array

object.log .length // if the object is on the console(Object.keys(userScore).length) // The output is 4

Reference

Object.keys() - JavaScript | MDN
Object.keys() メソッドは、指定されたオブジェクトが持つプロパティの 名前の配列を、通常のループで取得するのと同じ順序で返します。
タイトルとURLをコピーしました