Skip to content

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff 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 0 for the empty object", function() {
it("devuelve 0 para el objeto vacío", function() {
assert.strictEqual( sumSalaries({}), 0);
});
});
Original file line number Diff line number Diff 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
// reduce loops over array of salaries,
// adding them up
// and returns the result
// reduce recorre el array de salarios,
// sumándolos
// y devuelve el resultado
function sumSalaries(salaries) {
return Object.values(salaries).reduce((a, b) => a + b, 0) // 650
}
Expand Down
Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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 0 for an empty object", function() {
it("devuelve 0 para 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 );
});
});
Original file line number Diff line number Diff 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. Ignore symbolic properties, count only "regular" ones.
PD: Ignore propiedades simbólicas, solamente cuente las propiedades "regulares".

66 changes: 33 additions & 33 deletions 1-js/05-data-types/09-keys-values-entries/article.md
Original file line number Diff line number Diff 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 array of keys.
- [Object.values(obj)](mdn:js/Object/values) -- returns an array of values.
- [Object.entries(obj)](mdn:js/Object/entries) -- returns an array of `[key, value]` pairs.
- [Object.keys(obj)](mdn:js/Object/keys) -- devuelve un array de propiedades.
- [Object.values(obj)](mdn:js/Object/values) -- devuelve un array de valores.
- [Object.entries(obj)](mdn:js/Object/entries) -- devuelve un array de pares `[propiedad, valor]`.

Please note the distinctions (compared to map for example):
Tenga en cuenta las distinciones (en comparación con map, 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 a base of all complex structures in JavaScript. 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 una base de todas las estructuras complejas en JavaScript. 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" array objects, 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/entries ignore symbolic properties"
Just like a `for..in` loop, these methods ignore properties that use `Symbol(...)` as keys.
```warn header="Object.keys/values/entries ignoran 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 array of 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 array de ú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 for arrays, e.g. `map`, `filter` and others.
Los objetos carecen de muchos métodos que existen para los arrays, 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 array of key/value pairs from `obj`.
2. Use array methods on that array, e.g. `map`.
3. Use `Object.fromEntries(array)` on the resulting array to turn it back into an object.
1. Use `Object.entries(obj)` para obtener un array de pares propiedad/valor de `obj`.
2. Use métodos de array en ese array, p.ej. `map`.
3. Use `Object.fromEntries(array)` en el array resultante 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 fromEntries gives back the object
// convertir a array, map, y luego fromEntries nos 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.