[Javascript] Object

Suyeonยท2020๋…„ 8์›” 21์ผ
0

Javascript

๋ชฉ๋ก ๋ณด๊ธฐ
3/31

๐Ÿ’ซ ์ฒ˜์Œ๋ถ€ํ„ฐ ๊ผผ๊ผผํžˆ ๋‹ค์‹œ ๊ณต๋ถ€ํ•˜๋Š” javascript object

Syntax

1๏ธโƒฃ Trailing Comma

  • This helps with diffs in source control, like git.
  • If you add a new parameter to the end of that list, the only change you get is a new line.
let user = {
  name: "John",
  age: 30,
};

2๏ธโƒฃ Object with const can be changed

const user = {
  name: "John"
};

user.name = "Pete"; // (*)
alert(user.name); // Pete

3๏ธโƒฃ Computed properties

  • the name of the property is taken from the variable
let fruit = prompt("Which fruit to buy?", "apple");

let bag = {
  [fruit]: 5,
};

alert( bag.apple ); // 5 

// complex expression
let bag = {
  [fruit + 'Computers']: 5 // bag.appleComputers = 5
};

4๏ธโƒฃ In Operator

let obj = {
  test: undefined
};

alert( obj.test ); // undefined
alert( "test" in obj ); // true

5๏ธโƒฃ Order

  • Integer: sorted
  • non-integer: creation order
// Integer
let codes = {
  "49": "Germany",
  "41": "Switzerland",
  "44": "Great Britain",
  "1": "USA"
};

for (let code in codes) {
  alert(code); // 1, 41, 44, 49
}

// If you want integer not sorted
let codes = {
  "+49": "Germany",
  "+41": "Switzerland",
  "+44": "Great Britain",
  "+1": "USA"
};

Cloning an object

  • Primitive values: copied โ€œas a whole valueโ€.
  • Object: copied note object itselt but "reference"- adress in memory
// Primitive 
let message = "Hello!";
let phrase = message;

// Object
let user = { name: "John" };
let admin = user; // copy the reference. user and admin share the same an object

admin.name = 'Pete'; 
alert(user.name); // Pete

โœ”๏ธ How to duplicate an object itselt?

  • Object.assign()
  • Object.assign(dest, [src1, src2, src3...])
  • It copies the properties of all source objects src1, ..., srcN into the target dest.
  • let clone = Object.assign({}, user);

โœ”๏ธ Nested Cloning

  • Deep cloning is required
  • Using Lodash library is recommended.
const original = {
  name: 'Fiesta',
  car: {
    color: 'blue',
  },
}
const copied = Object.assign({}, original)

original.name = 'Focus'
original.car.color = 'yellow'

copied.name //Fiesta
copied.car.color //yellow

Shallow cloning

  • Object.assign()
  • const copied = { ...original }

Transforming

Object๋ฅผ array๋กœ ๋ฐ”๊พธ์–ด ์ž‘์—…์„ ์‹คํ–‰ํ•˜๊ณ  ์‹ถ์„ ๋•Œ (map, filter๋“ฑ)

  • Object.keys(obj) โ€“ returns an array of keys.
  • Object.values(obj) โ€“ returns an array of values.
  • Object.entries(obj) โ€“ returns an array of [key, value] pairs.
let prices = {
  banana: 1,
  orange: 2,
  meat: 4,
};

let doublePrices = Object.fromEntries(
  Object.entries(prices).map(([key, value]) => [key, value * 2])
);

alert(doublePrices.meat); // 8
profile
Hello World.

0๊ฐœ์˜ ๋Œ“๊ธ€