0

i want to build new list of objects with average value from another list of objects The original list :

original_list = [{"time":16485,"max_count":6,"min_count":4,"max_ca":10,"min_ca":8},{"time":16495,"max_count":12,"min_count":10,"max_ca":8,"min_ca":6},]

The new list i want to get

new_list = [{"time":16485,"average_count":5,"average_ca":9},{"time":16495,"average_count":11,"average_ca":7,]

I tried this code but it doesn't work

const new_list = [];
original_list.map((element) => { 'time': element.time, 'average_count': 
$(element.max_count)/2 + $(element.min_count)/2, 'average_ca': (element.max_ca)/2 + $(element.min_ca)/2 });

but i got lot of syntax error, any idea how i can get the result please

  • FWIW, one way to start sanity-checking things like this is to extract the `map` function into a standalone function. This would have shown the syntax error immediately. – Dave Newton Mar 30 '22 at 22:40

2 Answers2

2

You need to wrap the function body in parentheses. It should look like this:

const new_list = original_list.map((element) => ({ 'time': element.time, 'average_count': $(element.max_count)/2 + $(element.min_count)/2, 'average_ca': (element.max_ca)/2 + $(element.min_ca)/2 }));

Here are the docs on arrow functions

2pichar
  • 1,348
  • 4
  • 17
  • I tried this t new_list = original_list?.map((element: any) => ({ 'time': element.time, 'average_count': element.max_count/2 + element.min_count/2, 'average_ca': element.max_ca/2 + element.min_ca/2 })); it doesn't work as the result not add object to the list , but override – alpha.romeo Mar 31 '22 at 13:02
0

I'd do something like this:

const new_list = original_list.map((element) => ({
  time: element.time,
  average_count: (element.max_count + element.min_count) / 2,
  average_ca: (element.max_ca + element.min_ca) / 2,
}));
CDoe
  • 276
  • 1
  • 8