1 _.set(object, path, value) 2 # ? ? ? 3 4 设置对象的路径上的属性值.如果路径不存在,则创建它. 5 6 参数 7 1、object (Object): 待扩大的对象. 8 2、path (Array|string): 属性路径. 9 3、value (*): 需要设置的值. 10 返回值 11 (Object): 返回 object. 12 13 实例 14 var object = { ‘a‘: [{ ‘b‘: { ‘c‘: 3 } }] }; 15 16 _.set(object, ‘a[0].b.c‘, 4); 17 console.log(object.a[0].b.c); 18 // => 4 19 20 _.set(object, ‘x[0].y.z‘, 5); 21 console.log(object.x[0].y.z); 22 // => 5
以上是文档的说明
结合_.each()使用更高效;
代码如下:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>HTML5 Canvas绘制文本文字入门示例 6 </title> 7 </head> 8 <body> 9 <script src="lodash.js"></script> 10 <script> 11 var b = [ 12 {name:"222",age:22}, 13 {name:"sdfs22",age:2}, 14 {name:"24322",age:12}, 15 {name:"22fds",age:42} 16 ]; 17 var sort = {}; 18 19 _.each(b,function(item,i){ 20 var dis = 1; 21 _.set(sort,b[i].name,dis) 22 }); 23 console.log(sort); 24 </script> 25 </body> 26 </html>
最后结果返回一个对象;
时间: 2024-10-19 23:27:34