[英]javaScript startsWith method giving an error
I am getting an error when filtering an array with startsWith method. 使用startsWith方法过滤数组时出现错误。
Error: Cannot read property startsWith of undefined 错误:无法读取未定义的属性startsWith
Here is my array: 这是我的数组:
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
i was expecting to have all the records those start with 'ACCESS'. 我希望所有记录都以“ ACCESS”开头。
How to apply startsWith method on multiple objects having different properties within same array? 如何在同一数组中具有不同属性的多个对象上应用startsWith方法?
您需要检查Keyword
属性是否首先存在:
console.log(testdata.filter(d => d.Keyword && d.Keyword.startsWith('ACCESS')));
You have plenty of objects that don't have the KeyWord
property, so you have to account for those cases too: 您有许多没有
KeyWord
属性的对象,因此您也必须考虑这些情况:
testdata.filter(d => d.KeyWord && d.Keyword.startsWith('ACCESS'));
Or, if the KeyWord
property can potentially be of a type other than string: 或者,如果
KeyWord
属性可能是字符串以外的其他类型:
testdata.filter(d => typeof d.KeyWord === 'string' && d.Keyword.startsWith('ACCESS'));
there are some objects which does not have keyword
. 有些对象没有
keyword
。 First check of its existence. 首先检查其存在。
console.log(testdata1.filter(d =>d.Keyword ? d.Keyword.startsWith('ACCESS') : false))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.