[英]What is the syntax to find a value in an array of objects by a property?
在數組對象中查找值的語法是什么?
var pStData = []; pStData.push({ st: 'WV', geom: 'xxx' }); pStData.push({ st: 'TX', geom: 'yyy' }); var sGeom = pStData.find(pStData => pStData.st == 'TX').geom; console.log(sGeom);
在我的代碼中, pStData.find(pStData => pStData.st == 'TX')
是undefined
。
除了根本沒有 jQuery 之外,您將數組定義為對象數組。 像這樣定義一個對象:
var pStData = {};
pStData['WV'] = {geom: 'xxx'};
pStData['TX'] = {geom: 'yyy'};
然后你可以簡單地訪問
var sGeom = pStData['WV'].geom;
您也可以通過
var sGeom = pStData.WV.geom;
當然,如果您只是查找字符串值,則不需要定義對象,例如這也能正常工作。
var pStData = {};
pStData['WV'] = 'xxx';
pStData['TX'] = 'yyy';
但是,如果您稍后需要添加額外的數據值,將其定義為對象可以為您的代碼提供未來證明。 永遠不要害怕做一點未來的打樣,它可以在以后節省很多工作。
使用這個功能:
function findObjectInArrayByProperty(array, propertyName, propertyValue) {
return array.find((o) => { return o[propertyName] === propertyValue });
}
所以,在你的情況下:
function findObjectInArrayByProperty(array, propertyName, propertyValue) { return array.find((o) => { return o[propertyName] === propertyValue }); } var pStData = []; pStData.push({ st: 'WV', geom: 'xxx' }); pStData.push({ st: 'TX', geom: 'yyy' }); var resultObj = findObjectInArrayByProperty(pStData, "st", "TX"); console.log(resultObj);
輸出 -> { st: 'TX', geom: 'yyy' }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.