0

I am having array person of say 3 objects and form that i want to return objects named description. Now m using map to iterate over person, but what happens here is, if person is not having description then it returns undefined. I want at last to get array with only description objects(no undefined).

const person = [
{abc: 'abc',description:{}},
{qwe:'qwe', def:'def'},
{abcd: 'abcd',description:{}}
]

console.log(person.map(indivi => indivi.description))

1
  • Add a filter before map... Commented Sep 16, 2017 at 4:38

2 Answers 2

1

You could filter them out with .filter:

const person = [
    {abc: 'abc',description:{}},
    {qwe:'qwe', def:'def'},
    {abcd: 'abcd',description:{}}
]

const descriptions = person
    .filter(indivi => indivi.description)
    .map(indivi => indivi.description);

Sign up to request clarification or add additional context in comments.

Comments

0

You could apply a filter to remove objects not having a description property, before calling map on objects.

const person = [
{abc: 'abc',description:{}},
{qwe:'qwe', def:'def'},
{abcd: 'abcd',description:{}}
]

console.log(person.filter(t => t.description).map(indivi => indivi.description))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.