lodash用法系列2: 處理對象


Lodash用來操作對象和集合,比Underscore擁有更多的功能和更好的性能。

官網:https://lodash.com/
引用:<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
安裝:npm install lodash

首先通過npm安裝lodash:
npm i --save lodash

在js文件中引用lodash:
var _ = require('lodash');  

import * as _ from "lodash";

 目錄:

  1. 判斷參數是否是對象 isPlainObject
  2. 對象添加字段,相同字段值重寫 assign
  3. 對象添加字段,保持原來字段的值 defaults
  4. 對象合並 merge
  5. 對象:根據值,尋找鍵 findKey
  6. 對象查詢 find where
  7. 對象查詢:根據多個屬性值,獲取對象其他屬性值 result findWhere
  8. 遍歷對象 forOwn
  9. 遍歷對象,對象有父對象 forIn
  10. 獲取對象的所有鍵 keys
  11. 獲取對象所有值 values at
  12. 獲取對象中的某些字段 pick
  13. 刪除對象中的某些字段 omit
  14. 刪除對象中的某些鍵值對 reduce pick
  15. 對象的鍵值對轉換成數組元素 pairs
  16. 顛倒對象的鍵和值 invert
  17. 拷貝對象 clone
  18. 獲取一個對象的所有方法名 functions
  19. 從兩個具有相同鍵、相同鍵數量的對象中,取出對應的鍵、鍵值合並成一個新的對象,新的對象作為數組元素 map
  20. 對象中鍵值包含值或函數,取出對象的所有鍵值對方到一個數組中,鍵值是函數的執行該函數 rsult
  21. 根據鍵取出一個對象中間對應的函數 bindKey
  22. 把對象中的函數取出來放到一個數組中,再invoke它們  bindKey invoke

 

1. 判斷參數是否是對象 isPlainObject(obj)

function hello(greeting, person){
    if(_.isPlainObject(greeting)){
        person = greeting;
        greeting = 'hi';
    }
    return greeting + person.name;
}

hello('hello',{name:''});
hello({name:''});

2. 對象添加字段,相同字段值重寫  assign

var o = {
    name: '',
    age:22
};

_.assign(o, {occupation:''});

3. 對象添加字段,保持原來字段的值 defaults

var o = {
    name: 'a'
};

_.defaults(o, {
    name: 'b'
});

4. 對象合並 merge

var o1 = {
    states: {running: 'off'},
    names: ['a','b']
};

var o2 = {
    states: {off: 'on'},
    names: ['c','d']
};

var result = _.merge(o1, o2, function(dest, src){
    if(_.isArray(dest) && _.isArray(src)){
        return dest.concat(src);
    }
});

//{ states: { running: 'off', off: 'on' },names: [ 'a', 'b', 'c', 'd' ] }
console.log(result);

以上,o1和o2都有相同的字段,使用merge方法后會遍歷o1與o2的所有字段,但可喜的是:如果o2和o1的字段相同,並沒有進行簡單的重寫字段值,而是進行了合並。並且,還可以判斷o1和o2的字段類型,如果是數組,就把兩個數組concat。

5. 對象:根據值,尋找鍵 findKey

1. findkey方法接受對象

var obj = {
    a: {
        name: 'a',
        age:20
    },
    b: {
        description:''
    }
};

var result = _.findKey(obj, {name: 'a'});

//a
console.log(result);

2. findKey 方法接受匿名函數

var o = {
    name: 'a',
    age: 20
}

var result = _.findKey(o, function(value){
    return value === 'a';
});

//name
console.log(result);


// eg2:
var obj = {
    a: ['x','y'],
    b: ['m','n']
};

var search = 'x';

var result = _.findKey(obj, function(value){
    if(_.isArray(value)){
        return _.contains(value, search);
    } else {
        return value === search;
    }
});

//a
console.log(result);

6. 對象查詢 find where

var o = {
    1: {
        first:'',
        enabled:false
    },
    2: {
        first: '',
        enabled:true
    }
};

var result = _.find(o, 'enabled');
var result = _.where(o, {first: ''});

 7. 對象查詢:根據多個屬性值,獲取對象其他屬性值 result  findWhere

ar users = [
  { ‘user‘: ‘barney‘, ‘age‘: 36, ‘active‘: true },
  { ‘user‘: ‘fred‘,   ‘age‘: 40, ‘active‘: false }
];

_.result(_.findWhere(users, { ‘age‘: 36, ‘active‘: true }), ‘user‘);  // => ‘barney‘

_.result(_.findWhere(users, { ‘age‘: 40, ‘active‘: false }), ‘user‘);  // => ‘fred‘

8. 遍歷對象 forOwn

var o = {
    name: '',
    age:20,
    description:''
};

var result = [];

_.forOwn(o, function(value, key){
    result.push(key + ': ' + value);
});

console.log(result);

可見,forOwn方法forEach方法的不同之處在於匿名函數的第二個參數是鍵,不是索引

9. 遍歷對象,對象有父對象  forIn

unction Person(){
    this.full = function(){return this.first + ' ' + this.last;};
}

function Employee(first, last, occupation){
    this.first = first;
    this.last = last;
    this.occupation = occupation;
}

Employee.prototype = new Person();

var employee = new Employee('darren','ji','programmer'),
    resultOwn = [],
    resultIn = [];

_.forOwn(employee, function(value, key){
   resultOwn.push(key);
});

//[ 'first', 'last', 'occupation' ]
console.log(resultOwn);

_.forIn(employee, function(value, key){
   resultIn.push(key);
});

//[ 'first', 'last', 'occupation', 'full' ]
console.log(resultIn);

可見,forIn會遍歷包括父對象的字段,forOwn只遍歷當前對象的字段

10. 獲取對象的所有字段 keys

var o1 = {
    occupation: '',
    last:'',
    first:''
};
var o1Keys = _.keys(o1);   // 獲取所有鍵

var result1 = _.sortBy(o1Keys);  //所有鍵排序

//[ 'first', 'last', 'occupation' ]
console.log(result1);

11. 獲取對象所有值 values at

1. 直接獲取所有值

var o = {};
_.values(o);

2. 通過values把對象的值取出來,還用filter進行了排序,最后還把值包裹到html元素中 filter

var obj = {
    first: 'a',
    last: 'b',
    age:50
};

var result = _.map(_.filter(_.values(obj), _.isString), function(item){
    return '<strong>' + item + '</strong>';
});

//[ '<strong>a</strong>', '<strong>b</strong>' ]
console.log(result);

3. 獲取對象的所有key,然后據key或取值  at

var o2 = {
    occupation: 'manager',
    last: 'ji',
    first: 'darren'
};

//[ 'darren', 'ji', 'manager' ]
console.log(_.at(o2, _.sortBy(_.keys(o2))));

12. 獲取對象中的某些字段  pick

var o1 = {
    name: 'a',
    occupation:'b'
},

console.log(_.pick(o2, 'spcecialty'));  //{ spcecialty: 'c' }

13. 刪除對象中的某些字段 omit

// 去除值為 bool,o, null 的字段
var o = {
    name: 'a',
    age:0,
    occupation:null,
    enabled: true
};

var r = _.omit(o, function(value){
    return !(!_.isBoolean(value) && value);
});

console.log(r);  //{ name: 'a' }

1 4. 刪除對象中的某些鍵值對 reduce pick 

1. reduce

var object = {
    first: 'a',
    last: 'b',
    age: 41
},
allowed = ['first','last'];

var result = _.reduce(object,function(result, value, key){
    if(_.contains(allowed, key)){
        result[key] = value;
    }
    return result;
},{});

//{ first: 'a', last: 'b' }
console.log(result);

2. pick

var object = {
    first: 'a',
    last: 'b',
    age: 41
},
allowed = ['first','last'];

var result2 = _.pick(object, allowed);
//{ first: 'a', last: 'b' }
console.log(result2);

15. 對象的鍵值對轉換成數組元素 pairs

var o = {
    first: 'darren',
    last: 'ji',
    age:33
};

console.log(_.pairs(o)); //[ [ 'first', 'darren' ], [ 'last', 'ji' ], [ 'age', 33 ] ]

15. 顛倒對象的鍵和值 invert

var o = {
    first: 'a',
    last: 'b'
}

console.log(_.invert(o));  //{ a: "first", b: "last"}

16. 拷貝對象  clone

var o = {
    first: 'darren',
    last: 'ji'
},
clone = _.clone(o),

console.log(clone.first);  //darren

17. 獲取一個對象的所有方法名 functions

function Person(first, last){
    this.first = first;
    this.last = last;
}

Person.prototype.name = function(){
    return this.first + ' ' + this.last;
}

//[ 'name' ]
var result = _.functions(new Person('darren','ji'));

18. 從兩個具有相同鍵、相同鍵數量的對象中,取出對應的鍵、鍵值合並成一個新的對象,新的對象作為數組元素 map

var users = {},
    prefereces = {};
_.each(_.range(10), function () {
    var id = _.uniqueId('user-');
    users[id] = {type: 'user'};
    prefereces[id] = {email: !!(_.random())}
});

//users:{ 'user-1': { type: 'user' },'user-2': { type: 'user' },...}
//preference:{ 'user-1': { email: false },  'user-2': { email: true }...}
//users和preference的鍵是一樣的,鍵對應的值都是對象,鍵的數量也是一樣的

var result = _.map(users, function (value, key) {
    return _.extend({id: key}, prefereces[key]);
});

//[ { id: 'user-1', email: false },{ id: 'user-2', email: true },...]
console.log(result);

 19. 對象中鍵值包含值或函數,取出對象的所有鍵值對方到一個數組中,鍵值是函數的執行該函數 result

VS1. 通過isFunction來判斷鍵值是否是函數

// 通過isFunction來判斷鍵值是否是函數
var obj = {
    first: 'a',
    last: 'b',
    name: function () {
        return this.first + ' ' + this.last;
    },
    age: 22,
    retirement: 65,
    working: function () {
        return this.retirement - this.age;
    }
};

var result1 = _.map(obj, function (value, key) {
    var item = {};
    item[key] = _.isFunction(value) ? obj[key]() : value;
    return item;
});

//[ { first: 'a' },
//    { last: 'b' },
//    { name: 'a b' },
//    { age: 22 },
//    { retirement: 65 },
//    { working: 43 } ]
console.log(result1);

VS2. 直接調用result來執行鍵值函數

// 通過isFunction來判斷鍵值是否是函數
var obj = {
    first: 'a',
    last: 'b',
    name: function () {
        return this.first + ' ' + this.last;
    },
    age: 22,
    retirement: 65,
    working: function () {
        return this.retirement - this.age;
    }
};//[ { first: 'a' },
//    { last: 'b' },
//    { name: 'a b' },
//    { age: 22 },
//    { retirement: 65 },
//    { working: 43 } ]
var result2=_.map(obj, function(value, key){
   var item={};
    item[key]= _.result(obj,key);
    return item;
});

console.log(result2);

20.  根據鍵取出一個對象中間對應的函數 bindKey

// bindKey,根據鍵greet這個鍵把它對應的函數取出來。
var object = {
    'user': 'fred',
    'greet': function(greeting, punctuation) {
        return greeting + ' ' + this.user + punctuation;
    }
};

var bound = _.bindKey(object, 'greet','hi');  // _.bindKey(對象名稱,屬性名稱,參數, 參數...) //hi fred!
console.log(bound('!'));

21. 把對象中的函數取出來放到一個數組中,再invoke它們  bindKey invoke

var obj={
    firstName: 'a',
    lastName: 'b',
    first: function(){
        return this.firstName;
    },
    last: function(){
        return this.lastName;
    }
};

var methods =_.map(_.functions(obj),function(item){
    return [_.bindKey(obj, item)];
});

console.log(methods);

//[ 'a', 'b' ]
console.log(_.invoke(methods,0));

 

參考: https://www.cnblogs.com/darrenji/p/5011370.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM