Lodash——对象Object(二)

本文详细介绍了Lodash库中用于操作对象的各种方法,包括获取、设置、更新、删除属性,以及转换、筛选对象属性等高级功能,适用于JavaScript开发者提升代码效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1._.keys(object)

2._.keysIn(object)

3._.mapKeys(object, [iteratee=_.identity])

4._.mapValues(object, [iteratee=_.identity])

5._.merge(object, [sources])

6._.mergeWith(object, sources, customizer)

7._.omit(object, [props])

8._.omitBy(object, [predicate=_.identity])

9._.pick(object, [props])

10._.pickBy(object, [predicate=_.identity])

11._.result(object, path, [defaultValue])

12._.set(object, path, value)

13._.setWith(object, path, value, [customizer])

14._.transform(object, [iteratee=_.identity], [accumulator])

15._.unset(object, path)

16._.update(object, path, updater)

17._.updateWith(object, path, updater, [customizer])

18._.values(object)

19._.valuesIn(object)


1._.keys(object)

创建一个 object 的自身可枚举属性名为数组。

describe('_.keys(object)', function () {
        it('', function () {
            function Person() {
                this.a = 1;
                this.b = 2;
            }
            Person.prototype.c = 3;
            console.log(_.keys(new Person)); //[ 'a', 'b' ]
            console.log(_.keys('mandy')); //[ '0', '1', '2', '3', '4' ]
        })
    })
  • 非对象的值会被强制转换为对象。

2._.keysIn(object)

创建一个 object 自身 和 继承的可枚举属性名为数组。

describe('_.keysIn(object)', function () {
        it('', function () {
            function Person() {
                this.a = 1;
                this.b = 2;
            }
            Person.prototype.c = 3;
            console.log(_.keysIn(new Person)); //[ 'a', 'b', 'c' ]
            console.log(_.keysIn('mandy')); //[ '0', '1', '2', '3', '4' ]
        })
    })
  • 非对象的值会被强制转换为对象。

3._.mapKeys(object, [iteratee=_.identity])

反向版 _.mapValues。 这个方法创建一个对象,对象的值与object相同,并且 key 是通过 iteratee 运行 object 中每个自身可枚举属性名字符串 产生的。iteratee调用三个参数: (value, key, object)

 describe('_.mapKeys(object, [iteratee=_.identity])', function () {
        it('', function () {
            console.log(_.mapKeys({ 'a': 3, 'b': 4 }, function (value, key) {
                return key;
            })); 
            //{ a: 3, b: 4 }
            console.log(_.mapKeys({ 'a': 3, 'b': 4 }, function (value, key) {
                return value;
            }));
            //{ '3': 3, '4': 4 }
            console.log(_.mapKeys({ 'a': 3, 'b': 4 }, function (value, key) {
                return key + value;
            }));
            //{ a3: 3, b4: 4 }
        })
    })

4._.mapValues(object, [iteratee=_.identity])

创建一个对象,这个对象的key与object对象相同,值是通过 iteratee 运行 object 中每个自身可枚举属性名字符串产生的。 iteratee调用三个参数: (value, key, object)

describe('_.mapValues(object, [iteratee=_.identity])', function () {
        it('', function () {
            let object = {
                'teacher': { 'name': 'zhang', 'salary': '99999' },
                'student': { 'name': 'chen', 'salary': '66666' }
            }
            console.log(_.mapValues(object,function(o){return o.salary;}));
            //{ teacher: '99999', student: '66666' }
            console.log(_.mapValues(object,'salary'));
            //{ teacher: '99999', student: '66666' }
        })
    })

5._.merge(object, [sources])

该方法类似_.assign, 除了它递归合并 sources 来源对象自身和继承的可枚举属性到 object 目标对象。如果目标值存在,被解析为undefinedsources 来源对象属性将被跳过。数组和普通对象会递归合并,其他对象和值会被直接分配覆盖。源对象从从左到右分配。后续的来源对象属性会覆盖之前分配的属性。

describe('_.merge(object, [sources])', function () {
        it('', function () {
            let object ={'a':[{'b':1,'c':2},{'d':3}]};
            let other={'a':[{'b':11,'e':4},{'f':5,'g':6}]}
            console.log(_.merge(object,other));
            //{ a: [ { b: 11, c: 2, e: 4 }, { d: 3, f: 5, g: 6 } ] }
            console.log(object); 
            //{ a: [ { b: 11, c: 2, e: 4 }, { d: 3, f: 5, g: 6 } ] }
            console.log(other);
            //{ a: [ { b: 11, e: 4 }, { f: 5, g: 6 } ] }
        })
    })
  • 这方法会改变对象 object.

6._.mergeWith(object, sources, customizer)

该方法类似_.merge,除了它接受一个 customizer,调用以产生目标对象和来源对象属性的合并值。如果customizer 返回 undefined,将会由合并处理方法代替。 customizer调用与7个参数:(objValue, srcValue, key, object, source, stack)

 describe('_.mergeWith(object, sources, customizer)', function () {
        it('', function () {
            function customizer(objValue, srcValue) {
                if (_.isArray(objValue)) {
                    return objValue.concat(srcValue);
                }
            }
            let object = { 'a': [1], 'b': [2] };
            let other = { 'a': [3], 'b': [4] };
            console.log(_.mergeWith(object, other,customizer));  //{ a: [ 1, 3 ], b: [ 2, 4 ] }
            console.log(object); //{ a: [ 1, 3 ], b: [ 2, 4 ] }
        })
    })
  • 这方法会改变对象 object.

7._.omit(object, [props])

反向版 _.pick; 这个方法一个对象,这个对象由忽略属性之外的object自身和继承的可枚举属性组成。(注:可以理解为删除object对象的属性)。

describe('_.omit(object, [props])', function () {
        it('', function () {
            let object = { 'a': 1, 'b': 2, 'c': 3 }
            console.log(_.omit(object,['a','c'])); //{ b: 2 }
            console.log(object); //{ a: 1, b: 2, c: 3 }
        })
    })
  • 这方法不会改变对象 object.

8._.omitBy(object, [predicate=_.identity])

反向版 _.pickBy;这个方法一个对象,这个对象忽略 predicate(断言函数)判断不是真值的属性后,object自身和继承的可枚举属性组成。predicate调用与2个参数:(value, key)

 describe('_.omitBy(object, [predicate=_.identity])', function () {
        it('', function () {
            let object = { 'a': 1, 'b': '2', 'c': 3 }
            console.log(_.omitBy(object, _.isNumber)); //{ b: '2' }
            console.log(object); //{ a: 1, b: '2', c: 3 }
        })
    })

9._.pick(object, [props])

创建一个从 object 中选中的属性的对象。

describe('_.pick(object, [props])', function () {
        it('', function () {
            let object = { 'a': 1, 'b': '2', 'c': 3 }
            console.log(_.pick(object, ['a', 'c'])); //{ a: 1, c: 3 }
            console.log(object); //{ a: 1, b: '2', c: 3 }
        })
    })

10._.pickBy(object, [predicate=_.identity])

创建一个对象,这个对象组成为从 object 中经 predicate 判断为真值的属性。 predicate调用2个参数:(value, key)

 describe('_.pickBy(object, [predicate=_.identity])', function () {
        it('', function () {
            let object = { 'a': 1, 'b': '2', 'c': 3 }
            console.log(_.pickBy(object, _.isNumber)); //{ a: 1, c: 3 }
            console.log(object); //{ a: 1, b: '2', c: 3 }
        })
    })

11._.result(object, path, [defaultValue])

这个方法类似 _.get, 除了如果解析到的值是一个函数的话,就绑定 this 到这个函数并返回执行后的结果。

 describe('_.result(object, path, [defaultValue])', function () {
        it('', function () {
            let object = {'a':[{'b':{'c1':1,'c2':_.constant(2)}}]}
            _.result(object,'a[0].b.c1').should.equal(1);
            _.result(object,'a[0].b.c2').should.equal(2);
            _.result(object,'a[0].b.c3','default_value').should.equal('default_value');
            _.result(object,'a[0].b.c3',_.constant('default_value')).should.equal('default_value');
        })
    })

12._.set(object, path, value)

设置 object对象中对应 path 属性路径上的值,如果path不存在,则创建。 缺少的索引属性会创建为数组,而缺少的属性会创建为对象。 使用 _.setWith 定制path创建。

describe('_.set(object, path, value)', function () {
        it('', function () {
            let object = { 'a': [{ 'b': { 'c': 1 } }] };
            _.set(object,'a[0].b.c',2);
            object.a[0].b.c.should.equal(2);
            console.log(object); //{ a: [ { b: [Object] } ] }
            _.set(object,['x','0','y','z'],3);
            object.x[0].y.z.should.equal(3);
            console.log(object); //{ a: [ { b: [Object] } ], x: [ { y: [Object] } ] }
        })
    })
  •  这个方法会改变 object

13._.setWith(object, path, value, [customizer])

这个方法类似_.set,除了它接受一个 customizer,调用生成对象的 path。 如果 customizer 返回 undefined 将会有它的处理方法代替。 customizer 调用3个参数: (nsValue, key, nsObject)
 

describe('_.setWith(object, path, value, [customizer])',function(){
        it('',function(){
            let object={};
            _.setWith(object,"['a']['b']",1,Object);
            console.log(object); //{ a: { b: 1 } }
        })
    })
  • 这个方法会改变 object.

14._.transform(object, [iteratee=_.identity], [accumulator])

_.reduce的替代方法;此方法将转换object对象为一个新的accumulator对象,结果来自iteratee处理自身可枚举的属性。 每次调用可能会改变 accumulator 对象。如果不提供accumulator,将使用与[[Prototype]]相同的新对象。iteratee调用4个参数:(accumulator, value, key, object)。如果返回 falseiteratee 会提前退出。

describe('_.transform(object, [iteratee=_.identity], [accumulator])', function () {
        it('', function () {
            let array = [2, 3, 4];
            let result = _.transform(array, function (result, n) {
                result.push(n *= n);
                return n % 2 == 0;
            }, []);
            console.log(result); //[ 4, 9 ]
            result = _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function (result, value, key) {
                (result[value] || (result[value] = [])).push(key);
                console.log((result[value] || (result[value] = [])));
                //[ 'a' ]
                //[ 'b' ]
                //[ 'a', 'c' ]
            }, {});
            console.log(result); //{ '1': [ 'a', 'c' ], '2': [ 'b' ] }
        })
    })

15._.unset(object, path)

移除object对象 path 路径上的属性。

 describe('_.unset(object, path)', function () {
        it('', function () {
            let object = { 'a': [{ 'b': { 'c': { 'd': 1 } } }] }
            _.unset(object, ['a', [0], 'b', 'c', 'd']).should.equal(true);
            _.unset(object,'a[0].b.c').should.equal(true)
        })
    })
  • 这个方法会改变源对象 object

16._.update(object, path, updater)

该方法类似_.set,除了接受updater以生成要设置的值。使用 _.updateWith来自定义生成的新pathupdater调用1个参数:(value)

describe('_.update(object, path, updater)', function () {
        it('', function () {
            let object = { 'a': [{ 'b': { 'c': 2 } }] };
            _.update(object, 'a[0].b.c', item => item * item);
            object.a[0].b.c.should.equal(4);
            _.update(object, 'x[0].y.z', item => item ? item + 1 : 99);
            object.x[0].y.z.should.equal(99);
        })
    })
  • 这个方法会改变 object

17._.updateWith(object, path, updater, [customizer])

该方法类似_.update,不同之处在于它接受customizer,调用来生成新的对象的path。如果customizer返回undefined,路径创建由该方法代替。customizer调用有三个参数:(nsValue, key, nsObject) 。

 describe('_.updateWith(object, path, updater, [customizer])', function () {
        it('', function () {
            let object = {};
            _.updateWith(object, "['a']['b']",_.constant(4), Object);
            console.log(object); //{ a: { b: 4 } }
        })
    })
  • 这个方法会改变 object

18._.values(object)

创建 object 自身可枚举属性的值为数组。

describe('_.values(object)', function () {
        it('', function () {
            function Person() {
                this.a = 'a';
                this.b = 'b';
            }
            Person.prototype.c = 'c';
            console.log(_.values(new Person)); //[ 'a', 'b' ]
            console.log(_.values("mandy")); //[ 'm', 'a', 'n', 'd', 'y' ]
        })
    })
  • 注意: 非对象的值会强制转换为对象。

19._.valuesIn(object)

创建 object 自身和继承的可枚举属性的值为数组

describe('_.valuesIn(object)', function (){
        it('', function () {
            function Person() {
                this.a = 'a';
                this.b = 'b';
            }
            Person.prototype.c = 'c';
            console.log(_.valuesIn(new Person)); //[ 'a', 'b', 'c' ]
        })
    })
  • 注意: 非对象的值会强制转换为对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值