[英]What is the syntax to find a value in an array of objects by a property?
What is the syntax to find a value in an array object?在数组对象中查找值的语法是什么?
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);
In my code, pStData.find(pStData => pStData.st == 'TX')
is undefined
.在我的代码中,
pStData.find(pStData => pStData.st == 'TX')
是undefined
。
Other than no jQuery there at all, you're defining the array as an array of objects.除了根本没有 jQuery 之外,您将数组定义为对象数组。 Define an object like this:
像这样定义一个对象:
var pStData = {};
pStData['WV'] = {geom: 'xxx'};
pStData['TX'] = {geom: 'yyy'};
Then you can access simply by然后你可以简单地访问
var sGeom = pStData['WV'].geom;
You can also access it via您也可以通过
var sGeom = pStData.WV.geom;
Of course you don't need to define the object if you're only looking up a string value, for example this would work just as well.当然,如果您只是查找字符串值,则不需要定义对象,例如这也能正常工作。
var pStData = {};
pStData['WV'] = 'xxx';
pStData['TX'] = 'yyy';
However, defining it as an object does future proof your code, should you need to add extra data values later.但是,如果您稍后需要添加额外的数据值,将其定义为对象可以为您的代码提供未来证明。 Never be afraid to do a bit of future proofing, it can save a lot of work later.
永远不要害怕做一点未来的打样,它可以在以后节省很多工作。
Use this function:使用这个功能:
function findObjectInArrayByProperty(array, propertyName, propertyValue) {
return array.find((o) => { return o[propertyName] === propertyValue });
}
So, in your case:所以,在你的情况下:
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);
output -> { st: 'TX', geom: 'yyy' }输出 -> { st: 'TX', geom: 'yyy' }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.