2

I have an array of objects called reports that has an object reportId that is currently returning as a string. I would like to convert that object reportId to integers. How can I do this with an array of objects?

I've attempted to accomplish this with mapping. and using parseInt but I am not having success.

Here is an example of my code:

let reports = [ {reportId: "21", title: "Online", code: "ON" }, {reportId: "11", title: "Retail", code: "RE" }, {reportId: "61", title: "Walk-in", code: "WI" } ]



 let ids = reports.reportId.split(',').map(function (item) {
        return parseInt(item, 10);
    });
    
console.log(ids)

I am expecting a return of a new array that wil llist reportId as numbers instead of a string such as: [ 21, 11, 61 ]

2 Answers 2

2

You are over-complicating things; you just need to map each entry in reports to its reportId property and convert that to an integer

let reports = [ 
  {reportId: "21", title: "Online", code: "ON" },
  {reportId: "11", title: "Retail", code: "RE" },
  {reportId: "61", title: "Walk-in", code: "WI" } 
]

let ids = reports.map(function (item) {
  return parseInt(item.reportId, 10);
});
    
console.log(ids)

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

Comments

0

You have to map over reports, not reports.reportId.split. In fact, reports is an array, it does not have a named property called "reportId", only the objects inside the array have it.

const reports = [ {reportId: "21", title: "Online", code: "ON" }, {reportId: "11", title: "Retail", code: "RE" }, {reportId: "61", title: "Walk-in", code: "WI" } ];

const reportIds = reports.map(({ reportId }) => parseInt(reportId, 10));

console.log(reportIds);

Side note: use const over let, almost always!

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.