2.12 pick

5.12.1 语法:

_.pick(obj, *args);

2.12.2 说明:

pick方法将obj对象与*args的值进行匹配,返回一个对象,此对象包含所有匹配成功的属性,*args可为多个属性名,数组,函数。(数组可和属性名同时使用)

2.12.3 代码示例:

示例一:根据多个属性名进行匹配

var result = _.pick({ one: '一', two: '二', three: '三' }, "one", "two");
console.log(result) //=> {one: "一", two: "二"}

示例二:根据数组进行匹配

var result;
result = _.pick({ one: '一', two: '二', three: '三' }, ["one", "two", "three"]);
console.log(result) //=> {one: "一", two: "二", three: "三"}

示例三:根据函数进行匹配

var result = _.pick({ one: '一', two: 2, three: 3 }, function (value, key, list) {
    return typeof value === "number";
});
console.log(result); //=> {three: 3}

2.12.4 属性名,数组同时使用

var result = _.pick({ one: '一', two: '二', three: '三' }, "one", ["two"], "three");
console.log(result) //=> {one: "一", two: "二", three: "三"}

2.12.5 obj为数组的情况

var result = _.pick([1, 2], "0", "1");
console.log(result) //=> {0: 1, 1: 2}

2.12.6 obj为函数

var Child = function () { };
Child.prototype = {
    name: 'zhangsan'
}
var result = _.pick(new Child, "name");
console.log(result); //=> {name: "zhangsan"}

2.12.7 参数名前边有系统方法的时候(参数名前边有系统方法则需要执行系统方法)

var result;
result = _.pick({ one: '一', two: 2, three: 3 }, Math.abs, "one", "two", "three");
console.log(result); //=> {two: 2, three: 3}

// Math.abs是最后一个参数的时候(不执行系统方法)
result = _.pick({ one: '一', two: 2, three: 3 }, "one", "two", "three", Math.abs);
console.log(result); //=> {one: "一", two: 2, three: 3}

2.12.8 特殊情况

示例一:*args非属性名,数组,函数会返回什么呢?

var result = _.pick({ one: '一', two: '二', three: '三' }, true);
console.log(result) //=> {}

示例二:pick方法参数为空

var result = _.pick();
console.log(result) //=> {}