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#159

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
otmon76 merged 1 commit intojavascript-tutorial:masterfromotmon76:1.5.9
Jun 3, 2025
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,10 +1,10 @@
functionsumSalaries(salaries) {
functionsečtiProdeje(prodeje) {

letsum = 0;
for (letsalary of Object.values(salaries)) {
sum +=salary;
letsoučet = 0;
for (letprodej of Object.values(prodeje)) {
součet +=prodej;
}

returnsum;
returnsoučet;
}

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
describe("sumSalaries", function() {
it("returns sum of salaries", function() {
letsalaries = {
"John": 100,
"Pete": 300,
"Mary": 250
describe("sečtiProdeje", function() {
it("vrátí součet prodejů", function() {
letprodeje = {
"Jan": 100,
"Petr": 300,
"Marie": 250
};

assert.equal(sumSalaries(salaries), 650 );
assert.equal(sečtiProdeje(prodeje), 650 );
});

it("returns 0 for the empty object", function() {
assert.strictEqual(sumSalaries({}), 0);
it("pro prázdný objekt vrátí 0", function() {
assert.strictEqual(sečtiProdeje({}), 0);
});
});
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
```js run demo
functionsumSalaries(salaries) {
functionsečtiProdeje(prodeje) {

letsum = 0;
for (letsalary of Object.values(salaries)) {
sum +=salary;
letsoučet = 0;
for (letprodej of Object.values(prodeje)) {
součet +=prodej;
}

returnsum; // 650
returnsoučet; // 650
}

letsalaries = {
"John": 100,
"Pete": 300,
"Mary": 250
letprodeje = {
"Jan": 100,
"Petr": 300,
"Marie": 250
};

alert(sumSalaries(salaries) ); // 650
alert(sečtiProdeje(prodeje) ); // 650
```
Or, optionally, we could also get the sum using`Object.values`and `reduce`:
Nebo volitelně můžeme také získat součet použitím`Object.values`a `reduce`:

```js
// reduceloops over array of salaries,
//adding them up
//and returns the result
functionsumSalaries(salaries) {
return Object.values(salaries).reduce((a, b) => a + b, 0) // 650
// reducecykluje nad polem prodejů,
//sečte je
//a vrátí výsledek
functionsečtiProdeje(prodeje) {
return Object.values(prodeje).reduce((a, b) => a + b, 0) // 650
}
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,23 +2,23 @@ importance: 5

---

#Sum the properties
#Součet vlastností

There is a `salaries` object with arbitrary number of salaries.
Máme objekt `prodeje` obsahující libovolný počet prodejů.

Write the function `sumSalaries(salaries)` that returns the sum of all salaries using `Object.values`and the `for..of` loop.
Napište funkci `sečtiProdeje(prodeje)`, která vrátí součet všech prodejů, přičemž bude využívat `Object.values`a cyklus `for..of`.

If `salaries` is empty, then the result must be `0`.
Je-li objekt `prodeje` prázdný, výsledek musí být `0`.

For instance:
Příklad:

```js
letsalaries = {
"John": 100,
"Pete": 300,
"Mary": 250
letprodeje = {
"Jan": 100,
"Petr": 300,
"Marie": 250
};

alert(sumSalaries(salaries) ); // 650
alert(sečtiProdeje(prodeje) ); // 650
```

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
functioncount(obj) {
functionspočítej(obj) {
return Object.keys(obj).length;
}

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() {
assert.equal(count({a: 1, b: 2}), 2 );
describe("spočítej", function() {
it("spočítá počet vlastností", function() {
assert.equal(spočítej({a: 1, b: 2}), 2 );
});

it("returns 0 for an empty object", function() {
assert.equal(count({}), 0 );
it("pro prázdný objekt vrátí 0", function() {
assert.equal(spočítej({}), 0 );
});

it("ignores symbolic properties", function() {
assert.equal(count({ [Symbol('id')]: 1 }), 0 );
it("ignoruje symbolické vlastnosti", function() {
assert.equal(spočítej({ [Symbol('id')]: 1 }), 0 );
});
});
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,20 +2,20 @@ importance: 5

---

#Count properties
#Počet vlastností

Write a function `count(obj)` that returns the number of properties in the object:
Napište funkci `spočítej(obj)`, která vrátí počet vlastností v objektu:

```js
letuser = {
name: 'John',
age: 30
letuživatel = {
jméno: 'Jan',
věk: 30
};

alert(count(user) ); // 2
alert(spočítej(uživatel) ); // 2
```

Try to make the code as short as possible.
Snažte se napsat kód co nejkratší.

P.S.Ignore symbolic properties, count only "regular" ones.
P.S.Ignorujte symbolické vlastnosti, počítejte jen „obyčejné“.

112 changes: 56 additions & 56 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,103 +1,103 @@

# Object.keys, values, entries
#MetodyObject.keys, values, entries

Let's step away from the individual data structures and talk about the iterations over them.
Odhlédněme nyní od individuálních datových struktur a promluvme si o iteracích nad nimi.

In the previous chapter we saw methods `map.keys()`, `map.values()`, `map.entries()`.
V předchozí kapitole jsme viděli metody `mapa.keys()`, `mapa.values()`, `mapa.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.
Tyto metody jsou generické, existuje společná dohoda ohledně jejich používání pro datové struktury. Jestliže si sami vytvoříme vlastní datovou strukturu, měli bychom je implementovat také.

They are supported for:
Jsou podporovány v:

- `Map`
- `Set`
- `Array`
-mapách (`Map`)
-množinách (`Set`)
-polích (`Array`)

Plain objects also support similar methods, but the syntax is a bit different.
Podobné metody jsou podporovány i v planých objektech, ale jejich syntaxe je trochu jiná.

## Object.keys, values, entries

For plain objects, the following methods are available:
Pro plané objekty jsou k dispozici následující metody:

- [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) --vrací pole klíčů.
- [Object.values(obj)](mdn:js/Object/values) --vrací pole hodnot.
- [Object.entries(obj)](mdn:js/Object/entries) --vrací pole dvojic `[klíč, hodnota]`.

Please note the distinctions (compared to map for example):
Prosíme, všimněte si rozdílů (například ve srovnání s mapou):

|| Map| Object |
|-------------|------------------|--------------|
|Call syntax | `map.keys()` | `Object.keys(obj)`,but not `obj.keys()` |
|Returns| iterable |"real" Array |
| | Mapa | Objekt |
|----------------|---------------------|-----------------------------------------|
|Syntaxe volání | `mapa.keys()`| `Object.keys(obj)`,ale ne `obj.keys()` |
|Vrací |iterovatelný objekt | „opravdové“ pole |

The first difference is that we have to call`Object.keys(obj)`,and not `obj.keys()`.
Prvním rozdílem je, že musíme volat`Object.keys(obj)`,ne `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.
Proč tomu tak je? Hlavním důvodem je flexibilita. Pamatujte, že objekty jsou základem všech složitých struktur v JavaScriptu. Můžeme tedy mít svůj vlastní objekt, např.`data`, který implementuje svou vlastní metodu`data.values()`. A přesto na něm můžeme volat`Object.values(data)`.

The second difference is that `Object.*`methods return "real" array objects, not just an iterable. That's mainly for historical reasons.
Druhým rozdílem je, že metody `Object.*`vracejí „opravdová“ pole, ne jen iterovatelné objekty. Tak tomu je zejména z historických důvodů.

For instance:
Příklad:

```js
letuser = {
name: "John",
age: 30
letuživatel = {
jméno: "Jan",
věk: 30
};
```

- `Object.keys(user) = ["name", "age"]`
- `Object.values(user) = ["John", 30]`
- `Object.entries(user) = [ ["name","John"], ["age",30] ]`
- `Object.keys(uživatel) = ["jméno", "věk"]`
- `Object.values(uživatel) = ["Jan", 30]`
- `Object.entries(uživatel) = [ ["jméno","Jan"], ["věk",30] ]`

Here's an example of using`Object.values`to loop over property values:
Zde je příklad použití`Object.values`k vytvoření cyklu nad hodnotami vlastností:

```js run
letuser = {
name: "John",
age: 30
letuživatel = {
jméno: "Jan",
věk: 30
};

//loop over values
for (letvalue of Object.values(user)) {
alert(value); //John, then 30
//cyklus nad hodnotami
for (lethodnota of Object.values(uživatel)) {
alert(hodnota); //Jan, poté 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/entriesignorují symbolické vlastnosti"
Stejně jako cyklus `for..in`, i tyto metody ignorují vlastnosti, jejichž klíčem je`Symbol(...)`.

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.
Zpravidla nám to vyhovuje. Jestliže však chceme i symbolické klíče, existuje samostatná metoda[Object.getOwnPropertySymbols](mdn:js/Object/getOwnPropertySymbols), která vrací pole výhradně symbolických klíčů. Existuje i metoda[Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys), která vrací *všechny* klíče.
```


##Transforming objects
##Transformace objektů

Objects lack many methods that exist for arrays, e.g. `map`, `filter`and others.
Objekty postrádají mnohé metody, které existují pro pole, např. `map`, `filter`a jiné.

If we'd like to apply them, then we can use`Object.entries` followed by `Object.fromEntries`:
Pokud je chceme použít, můžeme použít`Object.entries`, po níž bude následovat `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`,to transform these key/value pairs.
3.Use`Object.fromEntries(array)` on the resulting array to turn it back into an object.
1.Použijte `Object.entries(obj)`k získání pole dvojic klíč/hodnota z `obj`.
2.Na tomto poli použijte metody polí, např. `map`,která tyto dvojice klíč/hodnota transformuje.
3.Na výsledné pole volejte`Object.fromEntries(pole)`, která z něj opět udělá objekt.

For example, we have an object with prices, and would like to double them:
Například máme objekt s cenami a rádi bychom je zdvojnásobili:

```js run
letprices = {
banana: 1,
orange: 2,
meat: 4,
letceny = {
banán: 1,
pomeranč: 2,
maso: 4,
};

*!*
letdoublePrices = Object.fromEntries(
//convert prices to array, map each key/value pair into another pair
//and then fromEntries gives back the object
Object.entries(prices).map(entry => [entry[0],entry[1] * 2])
letdvojnásobnéCeny = Object.fromEntries(
//převedeme na pole, zmapujeme každou dvojici klíč/hodnota na jinou dvojici
//a pak nám funkce fromEntries znovu vytvoří objekt
Object.entries(ceny).map(prvek => [prvek[0],prvek[1] * 2])
);
*/!*

alert(doublePrices.meat); // 8
```
alert(dvojnásobnéCeny.maso); // 8
```

It may look difficult at first sight, but becomes easytounderstand after you use it once or twice. We can make powerful chains of transforms this way.
Na první pohled to může vypadat obtížně, ale jakmiletojednou nebo dvakrát použijete, bude snadné tomu porozumět. Tímto způsobem můžeme vytvořit silné řetězce transformací.

[8]ページ先頭

©2009-2025 Movatter.jp