assign.ts
ts
export function assign<T>(obj: Partial<T>, ...objs: Partial<T>[]): T {
return Object.assign(obj, ...objs)
}
filter-object.js
js
const filterObject = (f, obj) => Object
.entries(obj)
.filter(([_, v]) => f(v))
.map(([k, v]) => ({[k]: v}))
.reduce((acc, obj) => Object.assign(acc, obj))
const obj = {a: 1, b: 2, c: 3}
filterObject(n => n == 2, obj)
// {b: 2}
const obj = {a: {age: 10}, b: {age: 15}, c: {age: 20}}
filterObject(({age}) => age < 20, obj)
// {a: {age: 10}, b: {age: 15}}
from-entries.js
js
// map + reduce
const fromEntries = arr => arr
.map(([k, v]) => ({[k]: v}))
.reduce((acc, obj) => Object.assign(acc, obj))
// reduce
const fromEntries = arr => arr
.reduce((obj, [k, v]) => {
return Object.assign(obj, {[k]: v})
}, {})
const arr = [['a', 1], ['b', 2], ['c', 3]]
fromEntries(arr) // {a: 1, b: 2, c: 3}
index-by.js
js
const indexBy = (f, arr) => arr
.map(obj => ({[f(obj)]: obj}))
.reduce((acc, obj) => Object.assign(acc, obj))
const data = [{id: 1},{id: 2}, {id: 3}]
indexBy(v => v.id, data)
// {1: {id: 1}, 2: {id: 2}, 3: {id: 3}}
map-keys.js
js
const mapKeys = (f, obj) => Object
.entries(obj)
.map(([k, v]) => ({[f(k)]: v}))
.reduce((acc, obj) => Object.assign(acc, obj))
const obj = {a: 1, b: 2, c: 3}
mapKeys(n => n.repeat(2), obj)
// {aa: 1, bb: 2, cc: 3}
map-values.js
js
const mapValues = (f, obj) => Object
.entries(obj)
.map(([k, v]) => ({[k]: f(v)}))
.reduce((acc, obj) => Object.assign(acc, obj))
const obj = {a: 1, b: 2, c: 3}
mapValues(n => n + 10, obj)
// {a: 11, b: 12, c: 13}
peek.ts
ts
const peek = function <T, K extends keyof T>(key: K, obj: T) {
return obj[key]
}
const obj = {a: 1, b: 2, c: 3}
console.log(peek('a', obj))
// 1
console.log(peek('b', obj))
// 2
pick.ts
ts
const pick = function <T, K extends keyof T>(keys: K[], obj: T) {
return keys
.map(key => ({[key]: obj[key]}))
.reduce((acc, obj) => Object.assign(acc, obj))
}
const obj = {a: 1, b: 2, c: 3}
console.log(pick(['a', 'b'], obj))
// {a: 1, b: 2}
pluck.ts
ts
const pluck = function <T, K extends keyof T>(keys: K[], obj: T): T[K][] {
return keys.map(key => obj[key])
}
const obj = {a: 1, b: 2, c: 3}
console.log(pluck(['a', 'b'], obj))
// [1, 2]