-1

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.

  • 3
    There is zero jQuery in your code. It also works as expected. – Guy Incognito Sep 16 at 22:09
  • sorry, i did not say jQuery is in my code. I am asking for a jQuery solution. – Doug Moore Sep 16 at 22:14
  • 1
    You don't need a jQuery solution if you create the array correctly... You're looking for a sledgehammer to crack a walnut. If you really want a jQuery solution, look up $.each – Steve Childs Sep 16 at 22:23
  • @DougMoore The problem you’re describing, any sensible solution, and your code are all completely unrelated to jQuery and should contain no jQuery. You’re working with basic JavaScript here. You’re asking for JavaScript solutions. – user4642212 Sep 16 at 22:43
  • Duplicate of Find object by id in an array of JavaScript objects. Your code works as-is. There is no issue. – user4642212 Sep 16 at 22:47
0

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;

皇冠hg0088代理网址You can also access it via

var sGeom = pStData.WV.geom;

皇冠hg0088代理网址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.

| improve this answer | |
  • @DougMoore You’re not using the { geom: "" } objects. – user4642212 Sep 16 at 22:40
0

皇冠hg0088代理网址Use this function:

 function findObjectInArrayByProperty(array, propertyName, propertyValue) {
      return array.find((o) => { return o[propertyName] === propertyValue });
 }

皇冠hg0088代理网址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);

皇冠hg0088代理网址output -> { st: 'TX', geom: 'yyy' }

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy皇冠hg0088代理网址

Not the answer you're looking for? Browse other questions tagged or ask your own question.