JavaScript Treats ๐Ÿฌ #1: ๋ฐฐ์—ด ๋ถ„ํ•ด๋กœ ๊ฐ์ฒด ๋ฐ˜๋ณตํ•˜๊ธฐ

6688 ๋‹จ์–ด tutorialwebdevprogrammingjavascript

์†Œ๊ฐœโœจ



์•ˆ๋…•ํ•˜์„ธ์š”, ์ €๋Š” ์ด์•ˆ์ž…๋‹ˆ๋‹ค! ์ €๋Š” ์ฃผ๋กœ JavaScript๋กœ ์•ฝ 11๋…„ ๋™์•ˆ ์ฝ”๋”ฉ์„ ํ•ด์™”์Šต๋‹ˆ๋‹ค. ๋‚˜๋Š” ๊ทธ ๋ช‡ ๋…„ ๋™์•ˆ ๋ช‡ ๊ฐ€์ง€ ๊นŒ๋‹ค๋กœ์šด ๋ฌธ์ œ์— ๋ถ€๋”ชํ˜”๊ธฐ ๋•Œ๋ฌธ์— "JavaScript Treats"์‹œ๋ฆฌ์ฆˆ๋ฅผ ๋งŒ๋“ค๊ธฐ๋กœ ๊ฒฐ์ •ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฌํ•œ ๋ฌธ์ œ์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์œ ์šฉํ•œ ์œ ํ‹ธ๋ฆฌํ‹ฐ ๊ธฐ๋Šฅ์ด ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

์˜ค๋Š˜์˜ ๊ฐ„์‹๐Ÿฌ



JavaScript์—์„œ Object๋ฅผ ๋ฐ˜๋ณตํ•˜๋Š” ๋ฐฉ๋ฒ•์—๋Š” ์—ฌ๋Ÿฌ ๊ฐ€์ง€๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ค๋Š˜์€ ์ œ๊ฐ€ ๊ฐ€์žฅ ์ข‹์•„ํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๋ณด์—ฌ๋“œ๋ฆฌ๊ฒ ์Šต๋‹ˆ๋‹ค.

const object = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
}

// convert object to a 2D array of [key, value] pairs.
const objectEntries = Object.entries(object);

// destructure object entry array into a key and value variable
objectEntries.forEach(([key, value]) => {
  console.log(key, value); // logs: "a 1"
})


ํ…Œ์ดํฌ ํ™ˆ ๊ธฐ๋Šฅ ๐Ÿ’พ




const iterateObject = (object, callback) => {
  Object.entries(object).forEach(callback);
}

const mapObject = (object, callback) => {
  return Object.entries(object).map(callback);
}

const reduceObject = (object, callback, defaultValue) => {
  return Object.entries(object).reduce(callback, defaultValue);
}


์‚ฌ์šฉ ์˜ˆ ๐Ÿ”ง




iterateObject(object, ([key, value]) => {
    console.log(key, value); // a 1
});

const mapped = mapObject(object, ([key, value]) => value);

console.log(mapped); // [1, 2, 3, 4]

const reduced = reduceObject(object, (final, [key, value]) => {
    return {
    ...final,
    [key]: value + 1,
  }
}, object);

console.log(reduced); // { a: 2, b: 3, c: 4, d: 5 }


๊ฒฐ๋ก  ๐Ÿ”š



์ด ์‹œ๋ฆฌ์ฆˆ์˜ ๋ชจ๋“  JavaScript Treats๋Š” ์—ฌ๊ธฐgithub repository์—์„œ ํ˜ธ์ŠคํŒ…๋ฉ๋‹ˆ๋‹ค.

๋‹น์‹ ์ด ์—ฌ๊ธฐ๊นŒ์ง€ ํ–ˆ๋‹ค๋ฉด, ๋ฐ”๋ผ๊ฑด๋Œ€ ๋‹น์‹ ์€ ๋‹น์‹ ์˜ ๋…์„œ๋ฅผ ์ฆ๊ฒผ๊ณ  ๋ฌด์–ธ๊ฐ€๋„ ๋ฐฐ์› ์Šต๋‹ˆ๋‹ค! ๋‹ค๋ฅธ ํ”Œ๋žซํผ์—์„œ ์ €๋ฅผ ํŒ”๋กœ์šฐํ•˜๊ณ  ์‹ถ์œผ์‹œ๋ฉด ์ €๋Š” ํŠธ์œ„์น˜์—์„œ ์ŠคํŠธ๋ฆฌ๋ฐํ•˜๊ณ  ํŠธ์œ„ํ„ฐ์—์„œ๋„ ์ €๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
์ฝ์–ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ