Home > Blockchain >  How to use Lodash to pick a key from an object with array of objects?
How to use Lodash to pick a key from an object with array of objects?

Time:01-29

I want to filter an object for my server response data. My object Included with array of objects.

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.

i try this but this is not working:

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

CodePudding user response:

You don't need Lodash for this.

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

CodePudding user response:

To access the object properties, You can achieve that with the help of dot(.) notation. For ex : object.key

But If you want to access each object property value from an array of Objects. In this case you have to iterate it with the help of Array.map() method.

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']

  • Related