使用startsWith方法过滤数组时出现错误。
错误:无法读取未定义的属性startsWith
这是我的数组:
let testdata = [
{
_id: "5d0876833827c2176cae90df",
MobileNumber: "965XXXXXXX",
Keyword: "ACCESSORIES",
DateStamp: 1560835715501,
id: "5d0876833827c2176cae90df"
},
{
_id: "5d0876833827c2176cae90e0",
MobileNumber: "965XXXXXXX",
Keyword:
"ACCESSORIES, ANNIVERSARY, BABY, BAGS, BATHING SUIT, BELTS,
BIRTHDAY, BIRTHDAY GIFT, BRAND, BRANDS, CHILDREN, CLOTHING,
DateStamp: 1560835715501,
id: "5d0876833827c2176cae90e0"
},
{
_id: "5d0876833827c2176cae90e1",
MobileNumber: "965XXXXXXX",
Keyword:
"ACCESSORIES, ANNIVERSARY, BABY, BAGS, BATHING SUIT, BELTS,
BIRTHDAY, BIRTHDAY GIFT, BRAND, BRANDS, CHILDREN, CLOTHING,
COMFORT, DEALS, DISCOUNT, DRESS, DRESSES, EXCHANGE, FASHION,
GIFT, GIFT CARD, GLASSES, HAIR.",
DateStamp: 1560835715501,
id: "5d0876833827c2176cae90e1"
},
{
_id: "5d08c7c79d70334824470fb4",
Name: "JOHN",
MobileNumber: "961XXXXXXX",
AnotherNumber: "NULL",
Email: "NULL",
FamilyName: "SMITH",
Gender: "M",
DateStamp: 1560856519847,
id: "5d08c7c79d70334824470fb4"
},
{
_id: "5d08c7c79d70334824470fb6",
Name: "ANTHONY",
MobileNumber: "961XXXXXXX",
AnotherNumber: "NULL",
Email: "NULL",
FamilyName: "JR",
Gender: "M",
DateStamp: 1560856519848,
id: "5d08c7c79d70334824470fb6"
},
{
_id: "5d0884ef3827c2176cb2a970",
MobileNumber: "96170359896",
PlateNumber: "NULL",
CarModel: "NULL",
CarType: "NULL",
DateStamp: 1560839407029,
id: "5d0884ef3827c2176cb2a970"
},
{
_id: "5d0884ef3827c2176cb2a971",
MobileNumber: "961XXXXXXXX",
PlateNumber: "P293676",
CarModel: "SEDAN",
ProductionDateOfCar: 1483228800000,
PurchaseDateOfCar: 1499281200000,
CarType: "HONDA",
DateStamp: 1560839407029,
id: "5d0884ef3827c2176cb2a971"
}
];
console.log(testdata.filter(d => d.Keyword.startsWith('ACCESS))); //getting error
我原本希望所有以'ACCESS'开头的记录。
如何对同一数组中具有不同属性的多个对象应用startsWith方法?
答案 0 :(得分:2)
您需要检查Keyword
属性是否首先存在:
console.log(testdata.filter(d => d.Keyword && d.Keyword.startsWith('ACCESS')));
答案 1 :(得分:2)
您有很多不具有KeyWord
属性的对象,因此您也必须考虑这些情况:
testdata.filter(d => d.KeyWord && d.Keyword.startsWith('ACCESS'));
或者,如果KeyWord
属性的类型可能不是字符串:
testdata.filter(d => typeof d.KeyWord === 'string' && d.Keyword.startsWith('ACCESS'));
答案 2 :(得分:0)
有些对象没有keyword
。首先检查它的存在。
console.log(testdata1.filter(d =>d.Keyword ? d.Keyword.startsWith('ACCESS') : false))