如果您喜欢使用库,请尝试lodash's _.unset。此示例直接来自文档:
移除对象路径的属性。
注意:此方法会改变对象。
var object = { 'a': [{ 'b': { 'c': 7 } }] };
_.unset(object, 'a[0].b.c');
// => true
console.log(object);
// => { 'a': [{ 'b': {} }] };
_.unset(object, ['a', '0', 'b', 'c']);
// => true
console.log(object);
// => { 'a': [{ 'b': {} }] };
在你的情况下,你会这样做:
var obj = { foo: 'FOO', bar: 'BAR', a: { b: 'B' } };
_.unset(obj, ['a', 'b']);
typeof obj.a.b === 'undefined'; // => true
如果你想用自己的代码来模仿它,你可以看看他们是如何实现的on line 4155 of the source:
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = isKey(path, object) ? [path] : castPath(path);
object = parent(object, path);
var key = toKey(last(path));
return !(object != null && hasOwnProperty.call(object, key)) || delete object[key];
}
不过,您必须查看其中使用的每个函数。