Adam Matan
Adam Matan

Reputation: 136509

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?

Upvotes: 9

Views: 12973

Answers (2)

Jack Evans
Jack Evans

Reputation: 1717

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:

Upvotes: 10

Adam Matan
Adam Matan

Reputation: 136509

.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' } ]

Upvotes: 4

Related Questions