UNPKG

967 BJavaScriptView Raw
1'use strict'
2
3var clone = require('./clone')
4var cloneWithout = require('./clone_without')
5
6/**
7 * Deletes a `keypath` from an `object` immutably.
8 *
9 * data = { users: { bob: { name: 'robert' } } }
10 * result = del(data, ['users', 'bob', 'name'])
11 *
12 * result = { users: { bob: {} } }
13 */
14
15module.exports = function del (object, keypath) {
16 var results = {}
17 var parents = {}
18 var i, len
19
20 for (i = 0, len = keypath.length; i < len; i++) {
21 if (i === 0) {
22 parents[i] = object
23 } else {
24 parents[i] = parents[i - 1][keypath[i - 1]]
25 if (!parents[i] || typeof parents[i] !== 'object') {
26 return object
27 }
28 }
29 }
30
31 for (i = keypath.length - 1; i >= 0; i--) {
32 if (i === keypath.length - 1) {
33 results[i] = cloneWithout(parents[i], keypath[i])
34 delete results[i][keypath[i]]
35 } else {
36 results[i] = clone(parents[i])
37 results[i][keypath[i]] = results[i + 1]
38 }
39 }
40
41 return results[0]
42}