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?
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:
.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' } ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With