Javascript object numbers as keys

Object.keys()

The Object.keys() static method returns an array of a given object’s own enumerable string-keyed property names.

Try it

Syntax

Parameters

Return value

An array of strings representing the given object’s own enumerable string-keyed property keys.

Description

Object.keys() returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon object . This is the same as iterating with a for. in loop, except that a for. in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.keys() is the same as that provided by a for. in loop.

If you need the property values, use Object.values() instead. If you need both the property keys and values, use Object.entries() instead.

Examples

Using Object.keys()

// Simple array const arr = ["a", "b", "c"]; console.log(Object.keys(arr)); // ['0', '1', '2'] // Array-like object const obj =  0: "a", 1: "b", 2: "c" >; console.log(Object.keys(obj)); // ['0', '1', '2'] // Array-like object with random key ordering const anObj =  100: "a", 2: "b", 7: "c" >; console.log(Object.keys(anObj)); // ['2', '7', '100'] // getFoo is a non-enumerable property const myObj = Object.create( >,  getFoo:  value()  return this.foo; >, >, >, ); myObj.foo = 1; console.log(Object.keys(myObj)); // ['foo'] 

If you want all string-keyed own properties, including non-enumerable ones, see Object.getOwnPropertyNames() .

Using Object.keys() on primitives

Non-object arguments are coerced to objects. Only strings may have own enumerable properties, while all other primitives return an empty array.

// Strings have indices as enumerable own properties console.log(Object.keys("foo")); // ['0', '1', '2'] // Other primitives have no own properties console.log(Object.keys(100)); // [] 

Note: In ES5, passing a non-object to Object.keys() threw a TypeError .

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

JavaScript Object Keys Tutorial – How to Use a JS Key-Value Pair

Amy Haddad

Amy Haddad

JavaScript Object Keys Tutorial – How to Use a JS Key-Value Pair

You can group related data together into a single data structure by using a JavaScript object, like this:

An object contains properties, or key-value pairs. The desk object above has four properties. Each property has a name, which is also called a key, and a corresponding value.

For instance, the key height has the value «4 feet» . Together, the key and value make up a single property.

The desk object contains data about a desk. In fact, this is a reason why you’d use a JavaScript object: to store data. It’s also simple to retrieve the data that you store in an object. These aspects make objects very useful.

This article will get you up and running with JavaScript objects:

  • how to create an object
  • how to store data in an object
  • and retrieve data from it.

Let’s start by creating an object.

How to Create an Object in JavaScript

I’ll create an object called pizza below, and add key-value pairs to it.

The keys are to the left of the colon : and the values are to the right of it. Each key-value pair is a property . There are three properties in this example:

Each property is separated by a comma. All of the properties are wrapped in curly braces.

This is the basic object syntax. But there are a few rules to keep in mind when creating JavaScript objects.

Object Keys in JavaScript

Each key in your JavaScript object must be a string, symbol, or number.

Take a close look at the example below. The key names 1 and 2 are actually coerced into strings.

It’s a difference made clear when you print the object.

console.log(shoppingCart); //Result:

There’s another rule to keep in mind about key names: if your key name contains spaces, you need to wrap it in quotes.

Take a look at the programmer object below. Notice the last key name, «current project name» . This key name contains spaces so, I wrapped it in quotes.

Object Values in JavaScript

A value, on the other hand, can be any data type, including an array, number, or boolean. The values in the above example contain these types: string, integer, boolean, and an array.

You can even use a function as a value, in which case it’s known as a method. sounds() , in the object below, is an example.

Now say you want to add or delete a key-value pair. Or you simply want to retrieve an object’s value.

You can do these things by using dot or bracket notation, which we’ll tackle next.

How Dot Notation and Bracket Notation Work in JavaScript

Dot notation and bracket notation are two ways to access and use an object’s properties. You’ll probably find yourself reaching for dot notation more often, so we’ll start with that.

How to Add a Key-Value Pair with Dot Notation in JavaScript

I’ll create an empty book object below.

To add a key-value pair using dot notation, use the syntax:

This is the code to add the key (author) and value («Jane Smith») to the book object:

Here’s a breakdown of the above code:

  • book is the object’s name
  • . (dot)
  • author is the key name
  • = (equals)
  • «Jane Smith» is the value

When I print the book object, I’ll see the newly added key-value pair.

I’ll add another key-value pair to the book object.

book.publicationYear = 2006; 

The book object now has two properties.

How to Access Data in a JavaScript Object Using Dot Notation

You can also use dot notation on a key to access the related value.

Consider this basketballPlayer object.

Say you want to retrieve the value “shooting guard.” This is the syntax to use:

Let’s put this syntax to use to get and print the «shooting guard» value.

console.log(basketballPlayer.position); //Result: shooting guard 

Here’s a breakdown of the above code:

console.log(basketballPlayer.name); //Result: James 

How to Delete a Key-Value Pair in JavaScript

To delete a key-value pair use the delete operator. This the syntax:

So to delete the height key and its value from the basketballPlayer object, you’d write this code:

delete basketballPlayer.height; 

As a result, the basketballPlayer object now has three key-value pairs.

console.log(basketballPlayer); //Result:

You’ll probably find yourself reaching for dot notation frequently, though there are certain requirements to be aware of.

When using dot notation, key names can’t contain spaces, hyphens, or start with a number.

For example, say I try to add a key that contains spaces using dot notation. I’ll get an error.

basketballPlayer.shooting percentage = "75%"; //Results in an error 

So dot notation won’t work in every situation. That’s why there’s another option: bracket notation.

How to Add a Key-Value Pair Using Bracket Notation in JavaScript

Just like dot notation, you can use bracket notation to add a key-value pair to an object.

Bracket notation offers more flexibility than dot notation. That’s because key names can include spaces and hyphens, and they can start with numbers.

I’ll create an employee object below.

Now I want to add a key-value pair using bracket notation. This is the syntax:

So this is how I’d add the key (occupation) and value (sales) to the employee object:

employee["occupation"] = "sales"; 

Here’s a breakdown of the above code:

  • employee is the object’s name
  • «occupation» is the key name
  • = (equals)
  • «sales» is the value

Below are several more examples that use bracket notation’s flexibility to add a variety of key-value pairs.

//Add multi-word key name employee["travels frequently"] = true; //Add key name that starts with a number and includes a hyphen employee["1st-territory"] = "Chicago"; //Add a key name that starts with a number employee["25"] = "total customers"; 

When I print the employee object, it looks like this:

With this information in mind, we can add the “shooting percentage” key to the basketballPlayer object from above.

You may remember that dot notation left us with an error when we tried to add a key that included spaces.

basketballPlayer.shooting percentage = "75%"; //Results in an error 

But bracket notation leaves us error-free, as you can see here:

basketballPlayer["shooting percentage"] = "75%"; 

This is the result when I print the object:

How to Access Data in a JavaScript Object Using Bracket Notation

You can also use bracket notation on a key to access the related value.

Recall the animal object from the start of the article.

Let’s get the value associated with the key, name . To do this, wrap the key name quotes and put it in brackets. This is the syntax:

Here’s the code you’d write with bracket notation: animal[«name»]; .

This is a breakdown of the above code:

console.log(animal["sounds"]()); //Result: meow meow undefined 

Note that sounds() is a method, which is why I added the parentheses at the end to invoke it.

This is how you’d invoke a method using dot notation.

console.log(animal.sounds()); //Result: meow meow undefined 

JavaScript Object Methods

You know how to access specific properties. But what if you want all of the keys or all of the values from an object?

There are two methods that will give you the information you need.

Use the Object.keys() method to retrieve all of the key names from an object.

We can use this method on the above runner object.

If you print the result, you’ll get an array of the object’s keys.

console.log(Object.keys(runner)); //Result: [ 'name', 'age', 'milesPerWeek', 'race' ] 

Likewise, you can use the Object.values() method to get all of the values from an object. This is the syntax:

Now we’ll get all of the values from the runner object.

console.log(Object.values(runner)); //Result: [ 'Jessica', 20, 40, 'marathon' ] 

We’ve covered a lot of ground. Here’s a summary of the key ideas:

  • Use objects to store data as properties (key-value pairs).
  • Key names must be strings, symbols, or numbers.
  • Values can be any type.

Access object properties:

Delete a property:

There’s a lot you can do with objects. And now you’ve got some of the basics so you can take advantage of this powerful JavaScript data type.

Источник

Читайте также:  Объявить переменную string php
Оцените статью