I have string:
city = 'Hải Phòng'
and an array that I get from an API which looks like this:
data = [{},{},{},{ MaTinhThanh: 'xx', TenTinhThanh: 'Hải Phòng' },{},{}]
I want to find an object in my data:
mycity = data.find( c=>c.TenTinhThanh.includes(city))
the above gives undefined
, but I expect
{ MaTinhThanh: 'xx', TenTinhThanh: 'Hải Phòng' }
My API endpoint is:
https://donhang.vnpost.vn/api/api/TinhThanh/GetAll
I am using visual code, Axios, nodejs
I also tried the getting the length of both strings:
data[3].TenTinhThanh.length` ====>11
city.length` ====>9
What is the problem?
CodePudding user response:
Your two strings don't contain the same characters, even though the appear to be visually the same:
const city = "Hải Phòng";
const objV = "Hải Phòng";
console.log(city === objV); // false
This is because you're using the precomposed forms of:
ả
(latin small letter a with hook above)ò
(latin small letter o with grave)
in your search string city
. These precomposed characters are legacy unicode characters, instead, you should be using the decomposed forms, which are the characters being used in your object value:
ả
(latin small letter aa
, followed by combining hook abovẻ
)ò
(latin small letter oo
, followed by combining grave accent̀
)
(yes, these are different to the ones listed previously). You can do this by updating your city
to hold "Hải Phòng"
(which uses the decomposed characters for ả
and ò
). If you can't decompose your string for whatever reason, you can use String.prototype.normalize()
on your input string or your object string, eg:
const city = 'Hải Phòng'.normalize("NFD"); // or just use `const city = "Hải Phòng";`
const data = [{},{},{},{ MaTinhThanh: 'xx', TenTinhThanh: 'Hải Phòng' },{},{}];
const mycity = data.find( c=>c.TenTinhThanh?.includes(city));
console.log(mycity);
CodePudding user response:
Check that the property exists in the first place, then match against that city value. It looks like there may have been something wrong with the encoding of the strings, because I received an error before I copied the city var value to the object.
Edit: It looks like another user laid out this issue in detail.
let city = 'Hải Phòng';
const data = [{},{},{},{ MaTinhThanh: 'xx', TenTinhThanh: 'Hải Phòng' },{},{}];
let mycity = data.find(c => c.TenTinhThanh && c.TenTinhThanh === city);
console.log(mycity);