{"id":"6b093ddebd4755deb67ee06e","slug":"flatten-object","title":"Spłaszczanie zagnieżdżonego obiektu","summary":"Zamieniamy zagnieżdżony obiekt JSON na płaską mapę ścieżka → wartość (np. do eksportu CSV albo porównania konfiguracji). Rekurencja lub jawny stos, liście i puste kontenery.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"easy","topics":["composite"],"techs":["typescript","javascript","python"],"tags":["recursion","objects","dfs","javascript"],"languages":[{"lang":"typescript","runner":"browser","starter":"type Json = null | boolean | number | string | Date | Json[] | { [key: string]: Json };\n\n/**\n * Flattens nested objects/arrays into { \"a.b[0].c\": leaf, ... }.\n * Empty objects/arrays are kept as values; the input is not modified.\n */\nfunction flatten(data: Json): Record<string, Json> {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":8,"tests":"test('nested objects', () => {\n  expect(flatten({ a: { b: 1, c: { d: 'x' } }, e: 2 })).toEqual({ 'a.b': 1, 'a.c.d': 'x', e: 2 });\n});\n\ntest('arrays use [i]', () => {\n  expect(flatten({ db: { host: 'localhost', ports: [5432, 5433] }, debug: false })).toEqual({\n    'db.host': 'localhost',\n    'db.ports[0]': 5432,\n    'db.ports[1]': 5433,\n    debug: false,\n  });\n  expect(flatten({ matrix: [[1], [2, 3]] })).toEqual({ 'matrix[0][0]': 1, 'matrix[1][0]': 2, 'matrix[1][1]': 3 });\n});\n\ntest('objects inside arrays', () => {\n  expect(flatten({ users: [{ name: 'Ola' }, { name: 'Jan', roles: ['dev'] }] })).toEqual({\n    'users[0].name': 'Ola',\n    'users[1].name': 'Jan',\n    'users[1].roles[0]': 'dev',\n  });\n});\n\ntest('array root', () => {\n  expect(flatten([1, { a: 2 }])).toEqual({ '[0]': 1, '[1].a': 2 });\n});\n\ntest('empty containers are kept, empty root gives {}', () => {\n  expect(flatten({ a: { b: {} }, c: [], d: null })).toEqual({ 'a.b': {}, c: [], d: null });\n  expect(flatten({})).toEqual({});\n  expect(flatten([])).toEqual({});\n});\n\ntest('null, falsy values and Date are leaves', () => {\n  const when = new Date('2026-01-02T03:04:05Z');\n  const flat = flatten({ meta: { created: when, deleted: null, count: 0, name: '' } });\n  expect(flat).toEqual({ 'meta.created': when, 'meta.deleted': null, 'meta.count': 0, 'meta.name': '' });\n  expect(flat['meta.created']).toBe(when);\n});\n\ntest('the input is not modified', () => {\n  const input = { a: { b: [1, { c: 2 }] } };\n  const copy = JSON.parse(JSON.stringify(input));\n  flatten(input);\n  expect(input).toEqual(copy);\n});\n\ntest('performance: 100 000 leaves', () => {\n  const data = {};\n  for (let i = 0; i < 400; i++) {\n    data['group' + i] = { items: Array.from({ length: 250 }, (_, j) => j) };\n  }\n  const flat = flatten(data);\n  expect(Object.keys(flat)).toHaveLength(100000);\n  expect(flat['group399.items[249]']).toBe(249);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Flattens nested objects/arrays into { \"a.b[0].c\": leaf, ... }.\n * Empty objects/arrays are kept as values; the input is not modified.\n */\nfunction flatten(data) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":8,"tests":"test('nested objects', () => {\n  expect(flatten({ a: { b: 1, c: { d: 'x' } }, e: 2 })).toEqual({ 'a.b': 1, 'a.c.d': 'x', e: 2 });\n});\n\ntest('arrays use [i]', () => {\n  expect(flatten({ db: { host: 'localhost', ports: [5432, 5433] }, debug: false })).toEqual({\n    'db.host': 'localhost',\n    'db.ports[0]': 5432,\n    'db.ports[1]': 5433,\n    debug: false,\n  });\n  expect(flatten({ matrix: [[1], [2, 3]] })).toEqual({ 'matrix[0][0]': 1, 'matrix[1][0]': 2, 'matrix[1][1]': 3 });\n});\n\ntest('objects inside arrays', () => {\n  expect(flatten({ users: [{ name: 'Ola' }, { name: 'Jan', roles: ['dev'] }] })).toEqual({\n    'users[0].name': 'Ola',\n    'users[1].name': 'Jan',\n    'users[1].roles[0]': 'dev',\n  });\n});\n\ntest('array root', () => {\n  expect(flatten([1, { a: 2 }])).toEqual({ '[0]': 1, '[1].a': 2 });\n});\n\ntest('empty containers are kept, empty root gives {}', () => {\n  expect(flatten({ a: { b: {} }, c: [], d: null })).toEqual({ 'a.b': {}, c: [], d: null });\n  expect(flatten({})).toEqual({});\n  expect(flatten([])).toEqual({});\n});\n\ntest('null, falsy values and Date are leaves', () => {\n  const when = new Date('2026-01-02T03:04:05Z');\n  const flat = flatten({ meta: { created: when, deleted: null, count: 0, name: '' } });\n  expect(flat).toEqual({ 'meta.created': when, 'meta.deleted': null, 'meta.count': 0, 'meta.name': '' });\n  expect(flat['meta.created']).toBe(when);\n});\n\ntest('the input is not modified', () => {\n  const input = { a: { b: [1, { c: 2 }] } };\n  const copy = JSON.parse(JSON.stringify(input));\n  flatten(input);\n  expect(input).toEqual(copy);\n});\n\ntest('performance: 100 000 leaves', () => {\n  const data = {};\n  for (let i = 0; i < 400; i++) {\n    data['group' + i] = { items: Array.from({ length: 250 }, (_, j) => j) };\n  }\n  const flat = flatten(data);\n  expect(Object.keys(flat)).toHaveLength(100000);\n  expect(flat['group399.items[249]']).toBe(249);\n});\n"},{"lang":"python","runner":"browser","starter":"def flatten(data) -> dict:\n    \"\"\"Flattens nested dicts/lists into {\"a.b[0].c\": leaf, ...}.\n    Empty dicts/lists are kept as values; the input is not modified.\"\"\"\n    raise NotImplementedError\n","testCount":8,"tests":"import copy\nfrom datetime import datetime, timezone\n\n\ndef check(data, expected):\n    got = flatten(data)\n    assert got == expected, f\"flatten({data!r}):\\n expected {expected!r}\\n got      {got!r}\"\n\n\ndef test_nested_dicts():\n    check({\"a\": {\"b\": 1, \"c\": {\"d\": \"x\"}}, \"e\": 2}, {\"a.b\": 1, \"a.c.d\": \"x\", \"e\": 2})\n\n\ndef test_lists_use_index_brackets():\n    check({\"db\": {\"host\": \"localhost\", \"ports\": [5432, 5433]}, \"debug\": False},\n          {\"db.host\": \"localhost\", \"db.ports[0]\": 5432, \"db.ports[1]\": 5433, \"debug\": False})\n    check({\"matrix\": [[1], [2, 3]]}, {\"matrix[0][0]\": 1, \"matrix[1][0]\": 2, \"matrix[1][1]\": 3})\n\n\ndef test_dicts_inside_lists():\n    check({\"users\": [{\"name\": \"Ola\"}, {\"name\": \"Jan\", \"roles\": [\"dev\"]}]},\n          {\"users[0].name\": \"Ola\", \"users[1].name\": \"Jan\", \"users[1].roles[0]\": \"dev\"})\n\n\ndef test_list_root():\n    check([1, {\"a\": 2}], {\"[0]\": 1, \"[1].a\": 2})\n\n\ndef test_empty_containers_are_kept_empty_root_gives_empty_dict():\n    check({\"a\": {\"b\": {}}, \"c\": [], \"d\": None}, {\"a.b\": {}, \"c\": [], \"d\": None})\n    check({}, {})\n    check([], {})\n\n\ndef test_none_falsy_values_and_datetime_are_leaves():\n    when = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)\n    flat = flatten({\"meta\": {\"created\": when, \"deleted\": None, \"count\": 0, \"name\": \"\"}})\n    assert flat == {\"meta.created\": when, \"meta.deleted\": None, \"meta.count\": 0, \"meta.name\": \"\"}, f\"got {flat!r}\"\n    assert flat[\"meta.created\"] is when, \"datetime should be copied as a leaf\"\n\n\ndef test_input_is_not_modified():\n    data = {\"a\": {\"b\": [1, {\"c\": 2}]}}\n    snapshot = copy.deepcopy(data)\n    flatten(data)\n    assert data == snapshot, f\"input changed: {data!r}\"\n\n\ndef test_performance_100k_leaves():\n    data = {f\"group{i}\": {\"items\": list(range(250))} for i in range(400)}\n    flat = flatten(data)\n    assert len(flat) == 100_000, f\"expected 100000 keys, got {len(flat)}\"\n    assert flat[\"group399.items[249]\"] == 249, \"last leaf\"\n"}],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:54.109Z","requestedLang":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Narzędzie do porównywania konfiguracji pokazuje różnice jako listę "},{"type":"text","text":"ścieżka = wartość","marks":[{"type":"code"}]},{"type":"text","text":". Potrzebna jest funkcja, która zagnieżdżony obiekt w stylu JSON zamieni na "},{"type":"text","text":"płaski","marks":[{"type":"bold"}]},{"type":"text","text":" obiekt, w którym kluczami są ścieżki do liści."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"flatten(data)","marks":[{"type":"code"}]},{"type":"text","text":" (Python: "},{"type":"text","text":"flatten(data)","marks":[{"type":"code"}]},{"type":"text","text":") zwraca nowy, płaski obiekt (słownik):"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"klucze obiektów łączymy kropką: "},{"type":"text","text":"{ a: { b: 1 } }","marks":[{"type":"code"}]},{"type":"text","text":" → "},{"type":"text","text":"{ \"a.b\": 1 }","marks":[{"type":"code"}]},{"type":"text","text":","}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"elementy tablic zapisujemy jako "},{"type":"text","text":"[i]","marks":[{"type":"code"}]},{"type":"text","text":" doklejone do ścieżki: "},{"type":"text","text":"{ tags: [\"x\", \"y\"] }","marks":[{"type":"code"}]},{"type":"text","text":" → "},{"type":"text","text":"{ \"tags[0]\": \"x\", \"tags[1]\": \"y\" }","marks":[{"type":"code"}]},{"type":"text","text":","}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"jeśli korzeniem jest tablica, ścieżki zaczynają się od "},{"type":"text","text":"[i]","marks":[{"type":"code"}]},{"type":"text","text":": "},{"type":"text","text":"[1, 2]","marks":[{"type":"code"}]},{"type":"text","text":" → "},{"type":"text","text":"{ \"[0]\": 1, \"[1]\": 2 }","marks":[{"type":"code"}]},{"type":"text","text":","}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"liście","marks":[{"type":"bold"}]},{"type":"text","text":" (napisy, liczby, wartości logiczne, "},{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"None","marks":[{"type":"code"}]},{"type":"text","text":" oraz inne obiekty niż zwykłe obiekty i tablice, np. "},{"type":"text","text":"Date","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"datetime","marks":[{"type":"code"}]},{"type":"text","text":") przepisujemy bez zmian,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"puste","marks":[{"type":"bold"}]},{"type":"text","text":" obiekty i tablice nie znikają – trafiają do wyniku jako wartości "},{"type":"text","text":"{}","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"[]","marks":[{"type":"code"}]},{"type":"text","text":","}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"pusty korzeń ("},{"type":"text","text":"{}","marks":[{"type":"code"}]},{"type":"text","text":" albo "},{"type":"text","text":"[]","marks":[{"type":"code"}]},{"type":"text","text":") daje pusty wynik,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"dane wejściowe nie mogą zostać zmienione."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Kolejność kluczy w wyniku nie ma znaczenia."}]},{"type":"heading","attrs":{"level":2,"id":"przyklad"},"content":[{"type":"text","text":"Przykład"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wejście"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wynik"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"{ \"db\": { \"host\": \"localhost\", \"ports\": [5432, 5433] }, \"debug\": false }","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"{ \"db.host\": \"localhost\", \"db.ports[0]\": 5432, \"db.ports[1]\": 5433, \"debug\": false }","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"{ \"a\": { \"b\": {} }, \"c\": [], \"d\": null }","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"{ \"a.b\": {}, \"c\": [], \"d\": null }","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"{ \"matrix\": [[1], [2, 3]] }","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"{ \"matrix[0][0]\": 1, \"matrix[1][0]\": 2, \"matrix[1][1]\": 3 }","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"ograniczenia"},"content":[{"type":"text","text":"Ograniczenia"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Głębokość zagnieżdżenia do 100, łącznie do 100 000 liści."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Klucze nie zawierają znaków "},{"type":"text","text":".","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"[","marks":[{"type":"code"}]},{"type":"text","text":" ani "},{"type":"text","text":"]","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"oczekiwana-zlozonosc"},"content":[{"type":"text","text":"Oczekiwana złożoność"}]},{"type":"paragraph","content":[{"type":"text","text":"Czas "},{"type":"text","text":"O(n · d)","marks":[{"type":"bold"}]},{"type":"text","text":", gdzie "},{"type":"text","text":"n","marks":[{"type":"code"}]},{"type":"text","text":" – liczba węzłów, "},{"type":"text","text":"d","marks":[{"type":"code"}]},{"type":"text","text":" – głębokość (koszt budowania napisów ścieżek); pamięć "},{"type":"text","text":"O(n · d)","marks":[{"type":"bold"}]},{"type":"text","text":" na wynik."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b093dc091bd8fbaf2a0c8b2","slug":"specification","title":"Specyfikacja: reguły biznesowe jako obiekty, które się składa"},{"id":"6b08bd3480884893657cc96a","slug":"flyweight","title":"Pyłek (Flyweight) – jak zmieścić w pamięci 60 tysięcy miejsc na stadionie"},{"id":"6b08bd3280884893657cc938","slug":"decorator","title":"Dekorator (Decorator) – dokładanie zachowania warstwa po warstwie"},{"id":"6b08bd3180884893657cc91a","slug":"composite","title":"Kompozyt (Composite) – drzewa, w których liść i gałąź wyglądają tak samo"},{"id":"6b08bd2f80884893657cc8f2","slug":"builder","title":"Budowniczy (Builder) – złożone obiekty krok po kroku"}],"topicsInfo":[{"slug":"composite","title":"Kompozyt","group":"structural","icon":"network"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:54.110Z","updatedAt":"2026-11-27T08:22:54.110Z"}