flat는 중첩 배열을 평탄화 시키는 매서드로
아래 예시를 보면 내장된 배열을 평탄화 시켜주는 작업을 한다.
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
flatten역시 flat와 비슷하게 평탄화 작업을 진행시켜주는 함수이다.
대상이 객체일 경우의 예제이다.
var flatten = require('flat')
flatten({
key1: {
keyA: 'valueI'
},
key2: {
keyB: 'valueII'
},
key3: { a: { b: { c: 2 } } }
})
위처럼 객체속 객체로 key/value가 나뉘어져 있던 객체가 있다면, flatten이 적용될경우
{
'key1.keyA': 'valueI',
'key2.keyB': 'valueII',
'key3.a.b.c': 2
}
같은 형태로 나오게 된다.
unflatten은 말그대로 flatten의 반대로 비평탄화를 시키는 함수이다.
let unflatten = require('flat').unflatten
unflatten({
'three.levels.deep': 42,
'three.levels': {
nested: true
}
})
위와 같은 경우의 객체를 unflatten하게 된다면
{
three: {
levels: {
deep: 42,
nested: true
}
}
}
같은 형태가 된다.