Lodash对象常用方法

1.对象合并
var object = {
    'a': [{ 'b': 2 }, { 'd': 4 }]
};
var other1 = {
     'b': [{ 'c': 3 }, { 'e': 5 }],
};
var other2 = {
     'b': [{ 'c': 3 }, { 'e': 5 }],
};
// 1. _.assign 和 _.assignIn 都是对象的合并继承,key一样,后面覆盖前面的,assignIn包含原型,都会改变object
_.assign(object,other1)// object=>{'a': [{ 'b': 2 }, { 'd': 4 }],'b': [{ 'c': 3 }, { 'e': 5 }]}
_.assignIn(object,other1)// object=>{'a': [{ 'b': 2 }, { 'd': 4 }],'b': [{ 'c': 3 }, { 'e': 5 }]}

//2._.merge数组和普通对象会递归合并,其他对象和值会被直接分配覆盖
_.merge(object,other1)// object=>{'a': [{ 'b': 2 }, { 'd': 4 }],'b': [{ 'c': 3 }, { 'e': 5 }]}
_.merge(object, other2);// object=> { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

//3._.defaults 合并自己没有的属性,有的则忽略,会改变原对象
_.defaults(object, { 'b': 2 }, { 'a': 3 });//{'a': [{ 'b': 2 }, { 'd': 4 }],'b': 2}

//4._.defaultsDeep递归分配默认属性
_.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });//=> { 'a': { 'b': 2, 'c': 3 } }

2.对象查找符合条件的属性key
const users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};
//1. _.findKey从头开始匹配,找到第一个符合条件key
 const res = _.findKey(object, function(o) { return o.age < 40; });//res=> barney
 const res = _.findKey(users, { 'age': 1, 'active': true }); // res=> 'pebbles'

//2. _.findLastKey从最后一个开始匹配,找到第一个符合条件key
const res = _.findKey(object, function(o) { return o.age < 40; });//res=> pebbles
const res = _.findKey(users, { 'age': 1, 'active' }); // res=> 'pebbles'
3.删除/添加/修改对象属性
var object = {
    'barney': { 'age': 36, 'active': true },
     'fred': { 'age': 40, 'active': false },
     'pebbles': { 'age': 1, 'active': true }
};
//1. _.unset 删除key
_.unset(object, 'fred')//object=> {'barney': { 'age': 36, 'active': true },'pebbles': { 'age': 1, 'active': true }}
_.unset(object,'barney.age')//object=> {'barney': { 'active': true },'pebbles': { 'age': 1, 'active': true }}

//2.  _.update 修改或者添加key值
//_.update(object, path, updater)参数 object要修改的对象,path要设置属性的路径, updater用来生成设置值的函数 
update(object, 'barney', function(n) { return '修改了'; })
//{barney: "修改了",'fred': { 'age': 40, 'active': false },'pebbles': { 'age': 1, 'active': true }}
update({}, 'barney', function(n) { return '添加'; })//{'barney':'添加'}

**

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值