Search code examples
javascriptjavascript-objects

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.


Solution

  • Other than no jQuery there at all, you're defining the array as an array of objects. 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.