JSON을 문자열로 변환기켜주는 Method입니다.

문자로 변환을 할 경우에, Serialize를 합니다.

예를 들면 new Date()의 경우엔, toJSON()이 실행되고, Serialize된 값을

문자로 변환한다.

JSON.stringify ( value [ , replacer [ , space ] ] )

value: 문자열을 만드는 JSON
replacer: 함수나 배열로 출력하는 요소를 지정
space: indent를 문자로 지정
function replacer(key, value) {
  // Filtering out properties
  if (typeof value === 'string') {
    return undefined;
  }
  return value;
}

var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
JSON.stringify(foo, replacer);
// '{"week":45,"month":7}'
JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}'



JSON.stringify({ a: 2 }, null, ' ');
// '{
//  "a": 2
// }'

JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
// returns the string:
// '{
//     "uno": 1,
//     "dos": 2
// }'

 

'Javascript' 카테고리의 다른 글

shallow copy & deep copy  (0) 2022.06.19
Object.assign 의 사용법  (0) 2022.06.19
배열 조작  (0) 2022.06.19

오브젝트는 참조복사를 한다.

오브젝트의 복사에 대해서 알고 있는 Object.assign은 shallow copy를 한다.

1계층 까지의 복사를 하게된다. 아래의 예로 차이점을 확인할 수 있다.

shallow copy

const output = (obj: {}) => {
  console.log(JSON.stringify(obj, null, 2));
};

const change1 = (obj: any) => {
  obj['x'] = 'change';
};

const change2 = (obj: any) => {
  obj['x']['xx'] = 'change';
};

const objectA = {
  x: {
    xx: 1,
    yy: 2,
  },
};

output(objectA);
// {
//   "x": {
//     "xx": 1,
//     "yy": 2
//   }
// }

change1(Object.assign({}, objectA));
output(objectA);
// {
//   "x": {
//     "xx": 1,
//     "yy": 2
//   }
// }

change2(Object.assign({}, objectA));
output(objectA);
// {
//   "x": {
//     "xx": "change",
//     "yy": 2
//   }
// }

deep copy

import * as lodash from 'lodash';

const output = (obj: {}) => {
  console.log(JSON.stringify(obj, null, 2));
};

const change1 = (obj: any) => {
  obj['x'] = 'change';
};

const change2 = (obj: any) => {
  obj['x']['xx'] = 'change';
};

const objectA = {
  x: {
    xx: 1,
    yy: 2,
  },
};

output(objectA);
// {
//   "x": {
//     "xx": 1,
//     "yy": 2
//   }
// }

change1(lodash.cloneDeep(objectA));
output(objectA);
// {
//   "x": {
//     "xx": 1,
//     "yy": 2
//   }
// }

change2(lodash.cloneDeep(objectA));
output(objectA);
// {
//   "x": {
//     "xx": 1,
//     "yy": 2
//   }
// }

'Javascript' 카테고리의 다른 글

JSON.stringify  (0) 2022.06.19
Object.assign 의 사용법  (0) 2022.06.19
배열 조작  (0) 2022.06.19

Object는 참조복사

const output = (obj: {}) => {
  console.log(JSON.stringify(obj, null, 2));
};

const change = (obj: any) => {
  obj['xxx'] = 1;
};

const objectA = {
  aaa: 10,
  bbb: 5,
};

output(objectA);
// {
//   "aaa": 10,
//   "bbb": 5
// }

change(objectA);

output(objectA);
// {
//   "aaa": 10,
//   "bbb": 5,
//   "xxx": 1
// }

Object.assign 의 복사

const output = (obj: {}) => {
  console.log(JSON.stringify(obj, null, 2));
};

const change = (obj: any) => {
  obj['xxx'] = 1;
};

const objectA = {
  aaa: 10,
  bbb: 5,
};

output(objectA);
// {
//   "aaa": 10,
//   "bbb": 5
// }

change(Object.assign({}, objectA));
--> 별도의 배열을 파라메터로 전달한다. 

output(objectA);
// {
//   "aaa": 10,
//   "bbb": 5,
// }

Object.assign 의 Merge

첫번째 파라메터에 두번째 이후의 파라메터를 Merge할 경우에 사용한다.

복사를 하고 싶을 경우엔, 첫번째 파라메터에 {} 를 지정한다.

const output = (obj: object) => {
  console.log(JSON.stringify(obj, null, 2));
};

const objectA = {
  aaa: 10,
  bbb: 5,
};
const objectB = {
  aaa: 20,
  ccc: 3,
};

output(Object.assign(objectA, objectB));
// {
//   "aaa": 20,
//   "bbb": 5,
//   "ccc": 3
// }

output(objectA);
// {
//   "aaa": 20,
//   "bbb": 5,
//   "ccc": 3
// }

output(objectB);
// {
//   "aaa": 20,
//   "ccc": 3
// }

'Javascript' 카테고리의 다른 글

JSON.stringify  (0) 2022.06.19
shallow copy & deep copy  (0) 2022.06.19
배열 조작  (0) 2022.06.19

Length | 배열수취득

const arr = [40, 30, 20, 10]
console.log(arr.length)

결과 : 4

 

Object 요소수취득 

Object.keys({}).length  // 0
Object.keys({'a': 123}).length  // 1

존재체크

IE11에서는 제공되지 않았습니다. 사용하고 싶은 경우에는 babel-polyfil를 도입하는 대응등이 필요합니다.

const arr = [40, 30, 20, 10]
console.log(arr.includes(20)) / true
console.log(arr.includes(50)) / false

위치확인과 존재확인

const arr = [40, 30, 20, 10]

console.log(arr.indexOf(20)) / 2
console.log(arr.indexOf(50)) / -1

if (arr.indexOf(20) !== -1){
  console.log('存在します') // 存在します 
}

if (arr.indexOf(50) === -1){
  console.log('存在しません') // 存在しません
}

결합

const arr = [40, 30, 20, 10]

console.log(arr.join()) / "40,30,20,10"
console.log(arr.join('-')) /"40-30-20-10"

배열의 복사 생성

복사이므로, arr2에 추가를 해도 arr1에는 변화가 없습니다.

const arr1 = [40, 30, 20, 10]
const arr2 = arr1.slice()
arr2.push(70)
console.log(arr1) / [40, 30, 20, 10]
console.log(arr2) / [40, 30, 20, 10, 70]

배열의 선두에 추가

const arr = [40, 30, 20, 10]

arr.unshift(1)
console.log(arr) / [1, 40, 30, 20, 10]

arr.unshift(3, 4)
console.log(arr) / [3, 4, 1, 40, 30, 20, 10]

배열의 꼬리에 추가

const arr = [40, 30, 20, 10]

arr.push(1)
console.log(arr) / [40, 30, 20, 10, 1]

arr.push(3, 4)
console.log(arr) / [40, 30, 20, 10, 1, 3, 4]

배열의 선두 삭제

const arr = [40, 30, 20, 10]

arr.shift()
console.log(arr) / [30, 20, 10]

arr.shift()
console.log(arr) / [20, 10]

배열의 꼬리 삭제

const arr = [40, 30, 20, 10]

arr.pop()
console.log(arr) / [40, 30, 20]

arr.pop()
console.log(arr) / [40, 30]

배열의 지정된 곳에 추가와 삭제

const arr = [40, 30, 20, 10]

// 2번째의 요소로부터 두개를 삭제
arr.splice(1, 2) 
console.log(arr) / [40, 10]

// 2번째의 요소로 부터 삭제하지 않고, 60을 추가 
arr.splice(1, 0, 60)
console.log(arr) / [40, 60, 10]

// 2번째의 요소로 부터 1개를 삭제하고, 80, 90을 추가
arr.splice(1, 1, 80, 90)
console.log(arr) / [40, 80, 90, 10]

다른 배열과의 결합

const arr = [40, 30, 20, 10]
const arr2 = [70, 50, 80]

console.log(arr.concat(arr2)) / [40, 30, 20, 10, 70, 50, 80]

일부를 발췌해서 배열 생성

const arr = [40, 30, 20, 10]

// 두번째부터 마지막까지 취득
console.log(arr.slice(1)) / [30, 20, 10]

// 2번째부터 3번째의 요소까지 취득
console.log(arr.slice(1, 3)) / [30, 20]

// 1번재부터 2번째의 요솎ㅏ지 취득
console.log(arr.slice(0, 2)) [40, 30]

배열에 고정값을 입력

console.log([4, 5, 1, 2].fill(100)) / [100, 100, 100, 100]
console.log([4, 5, 1, 2].fill(100, 1, 2)) / [4, 100, 1, 2]
console.log([4, 5, 1, 2].fill(100, 1, 3)) / [4, 100, 100, 2]

순서변화 ( 역순 )

const arr = [40, 50, 20, 10]
console.log(arr.reverse()) / [10, 20, 50, 40]

순서변화 ( sort )

// 오름순
const arr = [40, 50, 10, 20]
console.log(arr.sort()) / [10, 20, 40, 50]

// 내림순
const arr2 = [40, 50, 10, 20]
const compare = (x, y) => y - x
console.log(arr2.sort(compare)) / [50, 40, 20, 10]

배열 foreach

const arr = [40, 50, 10, 20]
arr.forEach(elm => {
  console.log(elm)
})

/40
/50
/10
/20


--> object를 이용할 경우
const obj = { 
  'name': 'jkim',  
  'old': 49
}

Object.keys(obj).forEach(key => {
  console.log(`key: ${key} value: ${obj[key]}`)
});

/"key: name value: jkim"
/"key: old value: 49"

배열 MAP 

const arr = [40, 50, 10, 20]
const arr2 = arr.map(elm => {
  return elm * 2
})

console.log(arr) / [40, 50, 10, 20]
console.log(arr2) / [80, 100, 20, 40]

배열 REDUCE | 한개의 값을 취득

const arr = [40, 50, 10, 20]
const initialValue = 100
const sum = arr.reduce((accumulator, currentValue) => {
  return accumulator + currentValue
}, initialValue)

console.log(sum) / 220

40 + 50 + 10 + 20 + 100 = 220

배열 Filter

const arr = [40, 50, 10, 20]
const arr2 = arr.filter(elm => {
  return elm > 20
})

console.log(arr2) / [40, 50]

배열 Find

const arr = [40, 50, 10, 20]
const val = arr.find(elm => {
  return elm > 20
})

console.log(val) / 40

배열 Some |  한개라도 해당할 경우, True

const arr = [40, 50, 10, 20]

console.log(arr.some(elm => {
  return elm > 20
})) / true

console.log(arr.some(elm => {
  return elm > 60
})) / false

배열 every |  모두가 해당할 경우, True

const arr = [40, 50, 10, 20]

console.log(arr.every(elm => {
  return elm > 20
})) / false 

console.log(arr.every(elm => {
  return elm < 60
})) / true

'Javascript' 카테고리의 다른 글

JSON.stringify  (0) 2022.06.19
shallow copy & deep copy  (0) 2022.06.19
Object.assign 의 사용법  (0) 2022.06.19

+ Recent posts