考虑以下数组的JSON表示:
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
}
]
假设我只想保留timestamp
和message
并省略ingestionTime
。在Python中,我会这样做:
>>> [ {'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'}]
如何在Javascript中进行相同的字段过滤?
答案 0 :(得分:2)
您可以使用对象解构来获取密钥的子集。
> 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' } ]
可以找到解构分配语法的文档:
答案 1 :(得分:0)
.map
with an arrow function does诀窍:
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' } ]