2017-08-08 67 views
1

我需要提取,從這個陣列如何從對象數組中提取鍵作爲數組?

const mylist = [ 
      { 
       "key": "", 
       "doc_count": 3 
      }, 
      { 
       "key": "IT", 
       "doc_count": 1 
      } 
     ] 

key值的數組:

["", "IT"] 

今天我用一個簡單的方法

finalList = [] 
_.forEach(myList, function (element) { 
    finalList.push(element.key) 
}) 

,但我看到lodash有幾種方法,其中差不多我的情況:_.zip/_.unzip_.fromPairs/_.toPairs_.zipObject

有沒有一種方法來簡化根據lodash方法的代碼?

回答

1

您可以通過使用Array#map的鍵提取到一個數組很容易地做到這一點沒有lodash:

const mylist = [{"key":"","doc_count":3},{"key":"IT","doc_count":1}]; 
 

 
const result = mylist.map(({ key }) => key); 
 

 
console.log(result);

如果你已經在你的項目中lodash可以使用_.map()

const mylist = [{"key":"","doc_count":3},{"key":"IT","doc_count":1}]; 
 

 
const result = _.map(mylist, 'key'); 
 

 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>