[英]Lodash. How to get array values from object if you know array keys?
例如,您有一個 object。
{ id: 1, firstName: 'John', lastName: 'Doe' }
如果您知道數組鍵,如何從 object 獲取數組? 你有數組鍵
['firstName', 'lastName']
你應該得到數組
['John', 'Doe']
我使用Lodash 。
你不需要lodash。
只需使用Array.prototype.map
從鍵數組中獲取值。
const obj = { id: 1, firstName: 'John', lastName: 'Doe' }; const filterKey = ['firstName', 'lastName']; console.log('FILTERED:', filterKey.map(key => obj[key]));
你可以_.at()
:
const obj = { id: 1, firstName: 'John', lastName: 'Doe' }; const keys = ['firstName', 'lastName']; const result = _.at(obj, keys); console.log('RESULT:', result);
<script src='https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js'></script>
const keys = Object.keys({ id: 1, firstName: 'John', lastName: 'Doe' }); const values = Object.values({ id: 1, firstName: 'John', lastName: 'Doe' }); console.log(keys) console.log(values)
Object.keys()
for getting all the keys of an object and Object.values()
to get an array with all the values that an object has.
您可以使用Object.keys
和Array.filter()
過濾您想要的鍵。
var filterKeys = ['firstName', 'lastName'] var obj = { id: 1, firstName: 'John', lastName: 'Doe' } var filteredObj = Object.keys(obj).filter(key => filterKeys.includes(key)).map(key => obj[key]) console.log(filteredObj);
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.