deep-get-set
Version:
Set and get values on objects via dot-notation strings.
132 lines (107 loc) • 2.62 kB
JavaScript
import test from 'tape'
import deep, { get, set } from './index.js';
test('default export', function (t) {
var obj = {}
t.equal(deep(obj, 'foo.bar', 'baz'), 'baz')
t.equal(obj.foo.bar, 'baz')
t.equal(deep(obj, 'foo.bar'), 'baz')
t.end()
})
test('deep gets', function (t) {
var obj = {
foo: 'bar',
bar: {
baz: {
beep: 'boop'
}
}
};
t.equal(get(obj, 'foo'), 'bar');
t.equal(get(obj, 'bar.baz.beep'), 'boop');
t.equal(get(obj, 'bar.baz.beep.yep.nope'), undefined);
t.end();
});
test('deep gets with array of paths', function (t) {
var obj = {
foo: 'bar',
bar: {
baz: {
beep: 'boop'
},
'baz.beep': 'blop'
}
};
t.equal(get(obj, ['bar', 'baz', 'beep']), 'boop');
t.equal(get(obj, ['bar', 'baz', 'beep', 'yep', 'nope']), undefined);
t.equal(get(obj, ['bar', 'baz.beep']), 'blop');
t.end();
})
test('deep sets', function (t) {
var obj = {
foo: 'bar',
bar: {
baz: {
beep: 'boop'
}
}
};
t.equal(set(obj, 'foo', 'yep'), 'yep');
t.equal(obj.foo, 'yep');
t.equal(set(obj, 'bar.baz.beep', 'nope'), 'nope');
t.equal(obj.bar.baz.beep, 'nope');
t.equal(set(obj, 'yep.nope', 'p'), 'p');
t.equal(obj.yep.nope, 'p');
t.end();
});
test('deep sets, strict', function (t) {
var obj = {};
t.throws(function () {
set(obj, 'yep.nope', 'p', true);
})
t.end();
});
test('deep sets with array of paths', function (t) {
var obj = {
foo: 'bar',
bar: {
baz: {
beep: 'boop'
}
}
};
t.equal(set(obj, 'foo', 'yep'), 'yep');
t.equal(obj.foo, 'yep');
t.equal(set(obj, ['bar', 'baz', 'beep'], 'nope'), 'nope');
t.equal(obj.bar.baz.beep, 'nope');
t.equal(set(obj, ['bar', 'baz.beep'], 'nooope'), 'nooope');
t.equal(obj.bar['baz.beep'], 'nooope');
t.end();
});
test('deep deletes', function (t) {
var obj = {
foo: 'bar',
bar: {
baz: {
beep: 'boop'
}
}
};
t.equal(set(obj, 'foo', undefined), undefined);
t.notOk(obj.foo);
t.equal(set(obj, 'bar.baz', undefined), undefined);
t.notOk(obj.bar.baz);
t.equal(get(obj, 'bar.baz.beep'), undefined);
t.end();
});
test('no prototype pollution', function (t) {
const obj = {}
set(obj, ['__proto__', 'a'], 1)
set(obj, [['__proto__'], 'b'], 2)
set(obj, 'constructor.prototype.c', 3)
t.equal(globalThis.a, undefined);
t.equal(globalThis.b, undefined);
t.equal(globalThis.c, undefined);
t.equal(get(obj, '__proto__.toString'), undefined)
t.equal(get(obj, 'constructor.prototype.toString'), undefined)
t.end();
});