我正在尝试使用ES6过滤以下数据:filter。
{
"EmailAddress": "joe@example.com",
"Name": "",
"Date": "2009-01-23 06:22:00",
"State": "Active",
"CustomFields": [
{
"Key": "[FirstName1]",
"Value": "joe"
},
{
"Key": "[LastName1]",
"Value": "bloggs"
}
]
}
要获取名字,我尝试了以下代码:
const firstName = subscriber.CustomFields.filter(cf => cf.Key='FirstName1')
但是,在那行代码之后,源更改为(请参阅LastName1更改为FirstName1):
{
"EmailAddress": "joe@example.com",
"Name": "",
"Date": "2009-01-23 06:22:00",
"State": "Active",
"CustomFields": [
{
"Key": "[FirstName1]",
"Value": "joe"
},
{
"Key": "[FirstName1]",
"Value": "bloggs"
}
]
}
我不明白通过过滤器提取数据会如何改变来源。我在这里忽略了一些基本的东西吗?
答案 0 :(得分:1)
您应该使用==
代替赋值(=
)。
const firstName = subscriber.CustomFields.filter(cf => cf.Key == 'FirstName1')
let subscriber = { "EmailAddress": "joe@example.com", "Name": "", "Date": "2009-01-23 06:22:00", "State": "Active", "CustomFields": [ { "Key": "[FirstName1]", "Value": "joe" }, { "Key": "[LastName1]", "Value": "bloggs" } ] }
const firstName = subscriber.CustomFields.filter(cf => cf.Key == '[FirstName1]');
console.log(firstName);