简体   繁体   中英

How to loop through an array of objects

Given this:

var results = [
  {
        "Title": "Battle of Baekgang",
        "Space": ["South Korea"]
    },
    {
        "Title": "Victory Tests",
        "Space": ["United Kingdom"]
    },
    {
        "Title": "Everett massacre",
        "Space": ["United States"]
    },
    {
        "Title": "Bologna massacre",
        "Space": ["Italy"]
    },
    {
        "Title": "Milano massacre",
        "Space": ["Italy"]
    }
];  

How would I loop it in order to say:

If Space value matching myNation {do this} ?

Having set var countries = ["Italy", United Kingdom", "South Korea"];

I have var regex = new RegExp(countries.join("|"), "i");

And I know i could do if(location.match(regex)) {

But I need to first store location I guess as the name of Space value

Or any other/better way?

UPDATE

I have a map with polygons and each polygons have classes like:

<path class="italy france germany">

I could have N classes names for each country, the json I get would have one object called Space with one or more countries in it, so I'd need to check if any of the json countries, matches any class in any polygons paths on my map and if so, the path should get a class active added to it.

If I understand your question properly, this should work:

var results = [{
        "Title": "Battle of Baekgang",
        "Space": ["South Korea"]
    }, {
        "Title": "Victory Tests",
        "Space": ["United Kingdom"]
    }, {
        "Title": "Everett massacre",
        "Space": ["United States"]
    }, {
        "Title": "Bologna massacre",
        "Space": ["Italy"]
    }, {
        "Title": "Milano massacre",
        "Space": ["Italy"]
    }
];

var countries = ["Italy", "United Kingdom", "South Korea"];
for (var i = 0; i < results.length; i++) {
    for (var j = 0; j < results[i]["Space"].length; j++) {
        if(countries.includes(results[i]["Space"][j])) {
            var matchedCountry = results[i]["Space"][j];
            var currentTitle = results[i]["Title"];
            //Do other stuff
        }
    }
}
 results.filter(
   ({Space})=>countries.includes(Space[0])
 ).forEach(el=>console.log(el))

Simply filter, then loop over the filtered :/


Update: you may create just one Space Set:

var spaces = new Set(
  results.reduce((acc,el)=>[...acc,...el.Space])
 );

Then you can just go over your elems:

 var els = document.querySelectorAll("path");
 els.forEach(function(el){
  if(el.className.split(" ").some(clas=>spaces.has(clas))){
   //do sth
  }
 });

This is the way I would go:

 var results = [ { "Title": "Battle of Baekgang", "Space": ["South Korea"] }, { "Title": "Victory Tests", "Space": ["United Kingdom"] }, { "Title": "Everett massacre", "Space": ["United States"] }, { "Title": "Bologna massacre", "Space": ["Italy"] }, { "Title": "Milano massacre", "Space": ["Italy"] } ]; var countries = ["Italy"]; for(var i = 0; i < results.length; i++) { if(countries.includes(results[i]["Space"][0])) { // the [0] is because of Space being an Array console.log(results[i]["Title"]); } } 

Below ES6 solution to find all entries that has Space within the countries array

 var countries = ["Italy", "United Kingdom", "South Korea"]; var regex = new RegExp(countries.join("|"), "i"); var results = [ { "Title": "Battle of Baekgang", "Space": ["South Korea"] }, { "Title": "Victory Tests", "Space": ["United Kingdom"] }, { "Title": "Everett massacre", "Space": ["United States"] }, { "Title": "Bologna massacre", "Space": ["Italy"] }, { "Title": "Milano massacre", "Space": ["Italy"] } ]; let matches = results.reduce((acc,{Space}) => regex.test(...Space)?acc.concat(...Space):acc, []); matches.forEach((i) => { jQuery(`path.${i.toLowerCase()}`).addClass('active') }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <path class="italy france germany"> </path> <path class="should not be updated"> </path> 

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