반응형

Javascript에서 객체배열(Object Array) 내부의 요소를 변경해야할 경우가 자주 발생합니다. 예를 들면 아래와 같은 객체 배열이 주어질 경우 특정 요소 또는 전체 요소의 age값을 변경할 필요가 있습니다.

const obj_array=[
  {
    name: "one",
    age: 1,
  },
  {
    name: "two",
    age: 2,
  },
  {
    name: "three",
    age: 3,
  }
]

 

이때 유용하게 사용할 수 있는 함수로 Map 메소드가 있습니다. 

Map은 내부에서 callback 함수를 실행한 결과를 가지고 새로운 배열을 만들 때 사용합니다.

 

1. 모든 요소의 값 변경하기

// age를 모두 4로
const result = obj_array.map(obj => {
  return {...obj, age: 4}
});
console.log(result); 
//[{ name: 'one', age: 4 },{ name: 'two', age: 4 },{ name: 'three', age: 4 }]

// age에 4배하기
const result = obj_array.map(obj => {
  return {...obj, age:obj.age*4}
});
console.log(result); 
//[{ name: 'one', age: 4 },{ name: 'two', age: 8 },{ name: 'three', age: 12 }]

 

2. 특정 요소들만 추출하기

const result = obj_array.map(obj => obj.name);
console.log(result); 
//[ 'one', 'two', 'three' ]

 

3. 특정 요소의 값 변경하기

age가 3인경우 값을 4로 바꾸기

const result = obj_array.map(obj => 
  {
    return obj.age===3 ? {...obj, age: 4} : obj
  });
console.log(result);
//[{ name: 'one', age: 1 },{ name: 'two', age: 2 },{ name: 'three', age: 4 }]

 

 

반응형

+ Recent posts