简体   繁体   English

罗达什。 如果您知道数组键,如何从 object 获取数组值?

[英]Lodash. How to get array values from object if you know array keys?

For example, you have an object.例如,您有一个 object。

{ id: 1, firstName: 'John', lastName: 'Doe' }

How to get an array from the object if you know array keys?如果您知道数组键,如何从 object 获取数组? You have array keys你有数组键

['firstName', 'lastName']

and you should get array你应该得到数组

['John', 'Doe']

I use Lodash .我使用Lodash

You don't need lodash.你不需要lodash。

Just use Array.prototype.map to get values from key array.只需使用Array.prototype.map从键数组中获取值。

 const obj = { id: 1, firstName: 'John', lastName: 'Doe' }; const filterKey = ['firstName', 'lastName']; console.log('FILTERED:', filterKey.map(key => obj[key]));

You can you _.at() :你可以_.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)
You don't need to use Lodash, using plain javascript will do it. 你不需要使用 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. 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.

You can use Object.keys and Array.filter() to filter the keys you want.您可以使用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);

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM