Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Python's List Comprehension in Javascript

Consider the following JSON representation of an array:

logMessages = [
   {
      "timestamp":1499776056977,
      "message":"Log message c7a09226",
      "ingestionTime":1499776058327
   },
   {
      "timestamp":1499777056977,
      "message":"Log message e5d5b51a3ae1",
      "ingestionTime":1499777058327
   },
   {
      "timestamp":1499778056977,
      "message":"Log message b79f4620935b",
      "ingestionTime":1499778058327
   }
]

Suppose that I'd like to keep only timestamp and message and omit ingestionTime. In Python, I would do:

>>> [ {'timestamp': o['timestamp'], 'message': o['message']} for o in logMessages]

[{'timestamp': 1499776056977, 'message': 'Log message c7a09226'},
 {'timestamp': 1499777056977, 'message': 'Log message e5d5b51a3ae1'}, 
 {'timestamp': 1499778056977, 'message': 'Log message b79f4620935b'}]

How do I do the same field filtering in Javascript?

like image 485
Adam Matan Avatar asked Jul 12 '17 10:07

Adam Matan


2 Answers

You can use object destructuring to obtain a subset of keys.

> logMessages= [ 
  { timestamp: 1499776056977,
    message: 'Log message c7a09226',
    ingestionTime: 1499776058327 },
  { timestamp: 1499777056977,
    message: 'Log message e5d5b51a3ae1',
    ingestionTime: 1499777058327 },
  { timestamp: 1499778056977,
    message: 'Log message b79f4620935b',
    ingestionTime: 1499778058327 } ]

> logMessages.map(({ timestamp, message }) => ({ timestamp, message }));

[ { timestamp: 1499776056977, message: 'Log message c7a09226' },
  { timestamp: 1499777056977,
    message: 'Log message e5d5b51a3ae1' },
  { timestamp: 1499778056977,
    message: 'Log message b79f4620935b' } ]

Documentation for Destructuring assignment syntax can be found:

  • Mozilla Develoepr Network
like image 199
Jack Evans Avatar answered Oct 05 '22 12:10

Jack Evans


.map with an arrow function does the trick:

logMessages= [ 
  { timestamp: 1499776056977,
    message: 'Log message c7a09226',
    ingestionTime: 1499776058327 },
  { timestamp: 1499777056977,
    message: 'Log message e5d5b51a3ae1',
    ingestionTime: 1499777058327 },
  { timestamp: 1499778056977,
    message: 'Log message b79f4620935b',
    ingestionTime: 1499778058327 } ]

> logMessages.map( (o) => {return {timestamp: o.timestamp, message: o.message}})
[ { timestamp: 1499776056977, message: 'Log message c7a09226' },
  { timestamp: 1499777056977,
    message: 'Log message e5d5b51a3ae1' },
  { timestamp: 1499778056977,
    message: 'Log message b79f4620935b' } ]
like image 21
Adam Matan Avatar answered Oct 05 '22 11:10

Adam Matan