简体   繁体   English

如何使用 Lodash 从带有对象数组的 object 中选择一个键?

[英]How to use Lodash to pick a key from an object with array of objects?

I want to filter an object for my server response data.我想为我的服务器响应数据过滤 object。 My object Included with array of objects.我的 object 包含在对象数组中。

const object1 = {
    _id: '12345',
    publicId: 'object-1',
    arrayOfObject2: [
        {
            _id: '12345',
            publicId: 'object-2',
            username: 'allen',
            password: '123456',
        },
    ],
};

For example i want to pick publicId from object1 and username from each object2 .例如,我想从object1中选择publicId ,从每个object2中选择username

i try this but this is not working:我试试这个,但这不起作用:

const pickedObject = lodash.pick(object1, ['publicId', 'arrayOfObject2.username']);

You don't need Lodash for this.为此,您不需要 Lodash。

const myObject = {
    ...object1,
    usernames: object1.arrayOfObject2.map(
        ({ username }) => username
    ),
};

To access the object properties, You can achieve that with the help of dot(.) notation.要访问 object 属性,您可以借助dot(.)符号来实现。 For ex: object.key例如: object.key

But If you want to access each object property value from an array of Objects.但是如果你想访问对象数组中的每个 object 属性值。 In this case you have to iterate it with the help of Array.map() method.在这种情况下,您必须借助Array.map()方法对其进行迭代。

Live Demo :现场演示

 const object1 = { _id: '12345', publicId: 'object-1', arrayOfObject2: [ { _id: '12345', publicId: 'object-2', username: 'allen', password: '123456', }, ], }; const res = object1.arrayOfObject2.map(({ username }) => username); console.log(object1.publicId); // prints 'object-1' console.log(res); // prints ['allen']

Update: After looking into the author comment on another answer, Top level object also a part of array of objects.更新:查看作者对另一个答案的评论后,顶级 object 也是对象数组的一部分。 Hence, You can iterate that as well by using lodash ._map method.因此,您也可以使用 lodash ._map方法对其进行迭代。

Live Demo :现场演示

 const arr = [{ _id: '12345', publicId: 'object-1', arrayOfObject2: [ { _id: '12345', publicId: 'object-2', username: 'allen', password: '123456', } ] }]; const res = _.map(arr, (obj) => { return { publicId: obj.publicId, arrayOfObject2: _.map(obj.arrayOfObject2, (obj2) => { return { username: obj2.username } }) } }); console.log(res);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

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

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