簡體   English   中英

羅達什。 如果您知道數組鍵,如何從 object 獲取數組值?

[英]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)
你不需要使用 Lodash,使用普通的 javascript 就可以了。 Use 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.keysArray.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM