Home > other >  Array.prototype.map() expects a return value from arrow function
Array.prototype.map() expects a return value from arrow function

Time:12-01

How to prevent this error, I am trying what ever I can, not possible to add return inside map.

Error:
Line 32:26: Array.prototype.map() expects a return value from arrow function array-callback-return

  const parseChartData = (field: string, data: string[][]) => {
    let chartData = [[field, 'count']];
    data.map((item: any) => {
      chartData.push([item._id, item._count])
    });
    return chartData;
  };

CodePudding user response:

If I understand correctly, you want to convert your data into pairs of [id, count], prepended by a header pair [field, 'count']?

Leaving type aside, you could:

  1. Convert data into chartData with map
  2. Prepend the header with array.unshift()
const chartData = data.map((item) => 
  [item._id, item._count]
);
chartData.unshift([field, 'count']);

As for types, make sure your parameter typing is consistent with how you use it:

  • data parameter is declared as string[][]
  • each of its items (hence a string[]) is used as item._id, item._count, i.e. we try accessing its _id and _count properties, which are not supposed to exist on string[]

Hence the very probable reason why you had to type each item as any.

If your data is actually an array of objects with _id and _count properties, then simply type it ad such:

data: Array<{ _id: string; _count: number }>

CodePudding user response:

if you don't want to map return data,Why not use forEach?please look up mdn docs

const parseChartData = (field: string, data: string[][]) => {
    let chartData = [[field, 'count']];
    data.forEach((item: any) => {
      chartData.push([item._id, item._count])
    });
    return chartData;
  };

  • Related