Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Object.keys, values, entries#275

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
describe("sumSalaries", function() {
it("returns sum of salaries", function() {
it("devuelve suma de salarios", function() {
let salaries = {
"John": 100,
"Pete": 300,
Expand All@@ -9,7 +9,7 @@ describe("sumSalaries", function() {
assert.equal( sumSalaries(salaries), 650 );
});

it("returns 0for the empty object", function() {
it("devuelve 0para el objeto vacío", function() {
assert.strictEqual( sumSalaries({}), 0);
});
});
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,12 +17,12 @@ let salaries = {

alert( sumSalaries(salaries) ); // 650
```
Or, optionally, we could also get the sum using`Object.values`and `reduce`:
Otra opción, también podemos obtener la suma utilizando`Object.values`y `reduce`:

```js
// reduceloops over arrayof salaries,
//adding them up
//and returns the result
// reducerecorre el arrayde salarios,
//sumándolos
//y devuelve el resultado
function sumSalaries(salaries) {
return Object.values(salaries).reduce((a, b) => a + b, 0) // 650
}
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,15 +2,15 @@ importance: 5

---

#Sum the properties
#Suma las propiedades

There is a `salaries`object with arbitrary number of salaries.
Hay un objeto `salaries`con un número arbitrario de salarios.

Write the function `sumSalaries(salaries)`that returns the sum of all salaries using`Object.values`and the`for..of` loop.
Escriba la función `sumSalaries(salaries)`que devuelva la suma de todos los salarios utilizando`Object.values`y el bucle`for..of`.

If `salaries`is empty, then the result must be `0`.
Si `salaries`está vacío, entonces el resultado debe ser `0`.

For instance:
Por ejemplo:

```js
let salaries = {
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
describe("count", function() {
it("counts the number of properties", function() {
it("cuenta el número de propiedades", function() {
assert.equal( count({a: 1, b: 2}), 2 );
});

it("returns 0for an empty object", function() {
it("devuelve 0para un objeto vacío", function() {
assert.equal( count({}), 0 );
});

it("ignores symbolic properties", function() {
it("ignora propiedades simbólicas", function() {
assert.equal( count({ [Symbol('id')]: 1 }), 0 );
});
});
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,9 @@ importance: 5

---

#Count properties
#Contar propiedades

Write a function `count(obj)`that returns the number of properties in the object:
Escriba una función `count(obj)`que devuelva el número de propiedades en el objeto:

```js
let user = {
Expand All@@ -15,7 +15,7 @@ let user = {
alert( count(user) ); // 2
```

Try to make the code as short as possible.
Trate de hacer el código lo más corto posible.

P.S. Ignoresymbolic properties, count only "regular" ones.
PD: Ignorepropiedades simbólicas, solamente cuente las propiedades "regulares".

66 changes: 33 additions & 33 deletions1-js/05-data-types/09-keys-values-entries/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,42 @@

# Object.keys, values, entries

Let's step away from the individual data structures and talk about the iterations over them.
Alejémonos de las estructuras de datos individuales y hablemos sobre las iteraciones sobre ellas.

In the previous chapter we saw methods `map.keys()`, `map.values()`, `map.entries()`.
En el capítulo anterior vimos métodos `map.keys()`, `map.values()`, `map.entries()`.

These methods are generic, there is a common agreement to use them for data structures. If we ever create a data structure of our own, we should implement them too.
Estos métodos son genéricos, existe un acuerdo común para usarlos para estructuras de datos. Si alguna vez creamos una estructura de datos propia, también deberíamos implementarla.

They are supported for:
Son compatibles para:

- `Map`
- `Set`
- `Array`

Plain objects also support similar methods, but the syntax is a bit different.
Los objetos simples también admiten métodos similares, pero la sintaxis es un poco diferente.

## Object.keys,values, entries
## Object.keys,valores, entradas

For plain objects, the following methods are available:
Para objetos simples, los siguientes métodos están disponibles:

- [Object.keys(obj)](mdn:js/Object/keys) --returns an arrayof keys.
- [Object.values(obj)](mdn:js/Object/values) --returns an arrayof values.
- [Object.entries(obj)](mdn:js/Object/entries) --returns an arrayof `[key, value]` pairs.
- [Object.keys(obj)](mdn:js/Object/keys) --devuelve un arrayde propiedades.
- [Object.values(obj)](mdn:js/Object/values) --devuelve un arrayde valores.
- [Object.entries(obj)](mdn:js/Object/entries) --devuelve un arrayde pares `[propiedad, valor]`.

Please note the distinctions (compared tomap for example):
Tenga en cuenta las distinciones (en comparación conmap, por ejemplo):

| | Map |Object |
| | Map |Objeto |
|-------------|------------------|--------------|
|Call syntax| `map.keys()` | `Object.keys(obj)`,but not `obj.keys()` |
|Returns | iterable | "real" Array |
|Sintaxis de llamada| `map.keys()` | `Object.keys(obj)`,pero no `obj.keys()` |
|Devuelve | iterable | "real" Array |

The first difference is that we have to call`Object.keys(obj)`,and not `obj.keys()`.
La primera diferencia es que tenemos que llamar`Object.keys(obj)`,y no `obj.keys()`.

Why so? The main reason is flexibility. Remember, objects are abaseof all complex structures inJavaScript.So we may have an object of our own like`data`that implements its own`data.values()` method. And we still can call `Object.values(data)`on it.
¿Por qué? La razón principal es la flexibilidad. Recuerda, los objetos son unabasede todas las estructuras complejas enJavaScript.Entonces, podemos tener un objeto propio como`data`que implementa su propio método`data.values()`. Y todavía podemos llamar a `Object.values(data)`en él.

The second difference is that`Object.*`methods return "real" arrayobjects, not just an iterable.That's mainly for historical reasons.
La segunda diferencia es que los métodos`Object.*`devuelven objetos de array"reales", no solo un iterable.Eso es principalmente por razones históricas.

For instance:
Por ejemplo:

```js
let user = {
Expand All@@ -49,38 +49,38 @@ let user = {
- `Object.values(user) = ["John", 30]`
- `Object.entries(user) = [ ["name","John"], ["age",30] ]`

Here's an example of using`Object.values`to loop over property values:
Aquí hay un ejemplo del uso de`Object.values`para recorrer los valores de propiedad:

```js run
let user = {
name: "John",
age: 30
};

//loop over values
//bucle sobre los valores
for (let value of Object.values(user)) {
alert(value); // John,then 30
alert(value); // John,luego 30
}
```

```warn header="Object.keys/values/entriesignore symbolic properties"
Just like a`for..in` loop, these methods ignore properties that use `Symbol(...)`as keys.
```warn header="Object.keys/values/entriesignoran propiedades simbólicas"
Al igual que un bucle`for..in`, estos métodos ignoran propiedades que utilizan `Symbol(...)`como nombre de propiedades.

Usually that's convenient. But if we want symbolic keys too, then there's a separate method [Object.getOwnPropertySymbols](mdn:js/Object/getOwnPropertySymbols)that returns an arrayof only symbolic keys. Also, there exist a method[Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys)that returns *all* keys.
Normalmente, esto es conveniente. Pero si también queremos propiedades simbólicas, entonces hay un método aparte [Object.getOwnPropertySymbols](mdn:js/Object/getOwnPropertySymbols)que devuelve un arrayde únicamente propiedades simbólicas. También existe un método[Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys)que devuelve *todas* las propiedades.
```


##Transforming objects
##Transformando objetos

Objects lack many methods that exist forarrays,e.g. `map`, `filter`and others.
Los objetos carecen de muchos métodos que existen para losarrays,p. Ej. `map`,`filter`y otros.

If we'd like to apply them, then we can use`Object.entries`followed by `Object.fromEntries`:
Si queremos aplicarlos, entonces podemos usar`Object.entries`seguido de `Object.fromEntries`:

1. Use `Object.entries(obj)`to get an arrayof key/value pairs from `obj`.
2. Usearray methods on thatarray,e.g. `map`.
3. Use `Object.fromEntries(array)`on the resultingarrayto turn it back into an object.
1. Use `Object.entries(obj)`para obtener un arrayde pares propiedad/valor de `obj`.
2. Usemétodos de array en esearray,p.ej. `map`.
3. Use `Object.fromEntries(array)`en elarrayresultante para convertirlo nuevamente en un objeto.

For example, we have an object with prices, and would like to double them:
Por ejemplo, tenemos un objeto con precios y nos gustaría duplicarlos:

```js run
let prices = {
Expand All@@ -91,12 +91,12 @@ let prices = {

*!*
let doublePrices = Object.fromEntries(
//convert to array, map,and then fromEntriesgives back the object
//convertir a array, map,y luego fromEntriesnos devuelve el objeto
Object.entries(prices).map(([key, value]) => [key, value * 2])
);
*/!*

alert(doublePrices.meat); // 8
```

It may look difficult from the first sight, but becomes easy to understand after you use it once or twice. We can make powerful chains of transforms this way.
Puede parecer difícil a primera vista, pero se vuelve fácil de entender después de usarlo una o dos veces. Podemos hacer poderosas cadenas de transformaciones de esta manera.

[8]ページ先頭

©2009-2025 Movatter.jp