2.14 pluck
2.14.1 语法:
_.pluck(list, key)
2.14.2 说明:
pluck方法根据key对list数组中的每个对象进行检索,返回检索成功的属性值,否则返回undefined,返回一个数组
- list为数组和arguments(数组中需要是对象类似:{x: 1})
- key是一个字符串
2.14.3 代码示例:
示例一:根据key来检索数组对象
var result;
// 操作数组对象
result = _.pluck([{name: 'moe', age: 30}, {name: 'curly', age: 50}], 'name');
console.log(result); //=> ["moe", "curly"]
//操作arguments
function abc() {
result = _.pluck([{name: 'moe', age: 30}, {name: 'curly', age: 50}], 'name');
console.log(result); //=> ["1.0", "2.0", "3.0"]
}
abc({name: 'moe', age: 30}, {name: 'curly', age: 50});
2.14.4 检索不到对应的key
var result = _.pluck([{ name: 'moe', age: 30 }, { name: 'curly', age: 50 }], 'sex');
console.log(result); //=> [undefined, undefined]
2.14.5 常见误区:
var result;
// list为字符串
result = _.pluck('ab', 'sex');
console.log(result); //=> [undefined, undefined]
// list为对象
result = _.pluck({ x: 1, y: 2 }, 'sex');
console.log(result); //=> [undefined, undefined]
2.14.5 特殊情况:
var result;
result = _.pluck([{ '[object Object]': 1 }, { x: 2 }], {});
console.log(result); //=> [1, undefined]
// list为null、true、undefined等等则返回一个空数组
result = _.pluck(null, 'sex');
console.log(result); //=> []