简体   繁体   中英

javascript string comparison issue in array.filter()

I have an array which contains following objects.

myArray = [
    { item: { id: 111557 } },
    { item2: { id: 500600 } }]

and I have a variable

targetItemID = '111557'

Note that one is string, and the ones in array are numbers. I'm trying to get the object having the correct item id.

Here is what I have tried,

 myArray = [ { item: { id: 111557 } }, { item2: { id: 500600 } }] targetItemID = '111557' var newArray = myArray.filter(x => { console.log(x.item.id.toString()) console.log(targetItemID.toString()) x.item.id.toString() === itemID.toString() }) console.log(newArray);

I expect all matching objects to be added to 'newArray'. I tried to check the values before comparison, They are both strings, they seem exactly same, but my newArray is still empty.

您需要返回过滤器才能工作:

return x.item.id.toString() === itemID.toString();
  • Your second object doesn't have an item property and should.
  • You need a return in your filter function.`
  • You must compare x.item.id against targetItemID , not itemID . Since you are using console.log() you would have seen and error of itemID id not defined ;).

 myArray = [ { item: { id: 111557 } }, { item: { id: 500600 } } ]; targetItemID = '111557' var newArray = myArray.filter(x => { //console.log(x.item.id.toString()) //console.log(targetItemID.toString()) return x.item.id.toString() === targetItemID.toString(); }); console.log(newArray);

There are a few issues here. First, not all your objects have an item property, so you'll need to check it exists. Second, you're comparing them against a non-existent itemID instead of targetItemID , and finally, and @bryan60 mentioned, if you open a block in an anonymous lambda, you need an explicit return statement, although, to be honest, you really don't need the block in this case:

var newArray =
    myArray.filter(x => x.item && x.item.id && x.item.id.toString() === targetItemID)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM