0

I have below array of object

const reports = [{id:3, name:'three', description:'three d', other: 'other 3'}, {id:2, name:'two', description:'two d', other: 'other 2'}];

and I want to filter out only 2 property of each object and below is my desired output

[{id:3, name:'three'}, {id:2, name:'two'}];

so tried this way

const reportList = reports.map((report) => {id,name} );
console.log(reportList);

throw error

ReferenceError: id is not defined

even I can achieve this by using this approach

 this.reportList = reports.map((report) => ({
                id: report.id,
                name: report.name,
                description: report.description
            }));

but here I need to write extra code, I want to use object accessor using key, can I achieve anyway?

1 Answer 1

1

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:

const reports = [{
  id: 3,
  name: 'three',
  description: 'three d',
  other: 'other 3'
}, {
  id: 2,
  name: 'two',
  description: 'two d',
  other: 'other 2'
}];

const reportList = reports.map(({id, name}) => ({
  id,
  name
}));
console.log(reportList);

Reference: Returning object literals by MDN

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

1 Comment

Thanks. got it now.

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.