let users = [
{ id: 11, name: 'Adam', age: 23, group: 'editor' },
{ id: 47, name: 'John', age: 28, group: 'admin' },
{ id: 85, name: 'William', age: 34, group: 'editor' },
{ id: 97, name: 'Oliver', age: 28, group: 'admin' }
];
John의 나이를 바꾸겠다고 하면, users[1].age = 29 이렇게 하면 끝나지만 아래와 같이 다른 방식을 써보자.
let updatedUsers = users.map(p=>p.id!==47?p:{...p, age: p.age+1})
// John is turning 29 now
한 개의 아이템을 바꾸는 것 대신 다른 값 하나를 포함하여 새로운 배열을 만들었다.
updatedUsers
== user
이렇게 참조해 비교가 가능하다.
리액트가 reconciliation process의 속도를 올리기 위해 이러한 방법을 사용했다고 한다.
배열을 키와 값으로 나눠 사용하는 것.
1)
const arr = {“id”: 0}
2)
const arr = [];
arr[id] = 0;
console.log(arr[id]);
var arr = {“one”: 1, “two”:2, “three”:3}
var y = arr[“one”];
for(var key in arr){
var value = arr[key];
return value
}
const content = [
{
title: 'Morning run',
id: 'id1',
desc: 'Meet at the park',
date: '2018-01-14T09:00:00.000Z',
location: 'Central park',
createdBy: '23432432',
},
{
title: 'Evening run',
id: 'id2',
desc: 'Meet by the station',
date: '2018-01-14T18:00:00.000Z',
location: 'Central station',
createdBy: '23432432',
},
];
위 와 같은 객체 배열이 있고, 나는 아래 처럼 만들고 싶다.:
const ouput = {‘id1’: ‘Morning run’, ‘id2’:’Evening run’}
방법:
const output = content.reduce((acc, k)=>(
acc[k.id] = k.title;
return acc;
),{});
참고사항
연관배열의 length는 정확한 값을 갖고 있지 않다.
let len = 0;
for(var idx in arr){
len++;
}
arr.