简体   繁体   中英

access javascript array element by JSON object key

I have an array that looks like this

var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]

I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)

Zips[rows[i].Zipcode].Count

I know that's not right and am hoping that there is a solution without looping through the result set every time?

Thanks

I know that's not right and am hoping that there is a solution without looping through the result set every time?

No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:

var filteredZips = Zips.filter(function(element) {
    return element.Zip == 92880;
});
if (filteredZips.length > 0) {
    // we have found a corresponding element
    var count = filteredZips[0].count;
}

If you had designed your object in a different manner:

var zips = {"92880": 1, "91710": 3, "92672": 0 };

then you could have directly accessed the Count :

var count = zips["92880"];

In the current form, you can not access an element by its ZIP-code without a loop.

You could transform your array to an object of this form:

var Zips = { 92880: 1, 91710: 3 }; // etc.

Then you can access it by

Zips[rows[i].Zipcode]

To transform from array to object you could use this

var ZipsObj = {};
for( var i=Zips.length; i--; ) {
  ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}

Couple of mistakes in your code.

  1. Your array is collection of objects
  2. You can access objects with their property name and not property value ie Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip .

If you want to find the value you have to loop

If you want to keep the format of the array Zips and its elements

var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
    MappedZips[Zips[i].Zip] = Zips[i];
} 

MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}

// then you can get Count by O(1)
alert(MappedZips[92880].Count);

// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);

jsFiddle example

function getZip(zips, zipNumber) {
  var answer = null;

  zips.forEach(function(zip){
    if (zip.Zip === zipNumber) answer = zip;
  });

  return answer;
}

This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.

你有尝试过吗?

Zips[i].Zip.Count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM