简体   繁体   中英

Converting each method in Jquery to Javascript for loop

$.each(data.features[i].properties, function(key, val){
  items[i][j].push(val);
}

I'm using this each method in my code with the function which has key and val as the parameters of the function. I want to convert this to a for loop in TypeScript, but I can't figure out how to get the key and val parameters as well.

var heads = [];
var items:any[] = [];
$.each( data.features[0].properties, function( key, val ) { 
  heads.push(key);
});
for(let i=0; i<data.features.length; i++){
  //$.each(data.features[i].properties, function(key, val)
  for(let j=0; j<data.features[i].properties.length; j++){
    items[i][j].push(val);
  }
}

This is what I'm trying to implement.

I'm getting a geoJSON file in data. It has several features and each feature has some properties which I want to push in the array.

each method of jQuery can iterate both, arrays and objects. It's not reasonable to replace it with a simple loop, it's better to wrap the loop in a function to create a closure for the parameters. The code below shows the basic jQuery-style each iteration, you can extend it to bind this value too.

 const arr = [0, 1, 2, 3], obj = {a: 'a', 'b': 'b', c: 'c', d: 'd'}, arrRes = [], objRes = []; function each(object, callback) { const keys = Object.keys(object), // Get an array of the keys of array or object end = keys.length; for (let index = 0; index < end; index++) { // Call the callback with parameters, exit if the callback returns false if (callback(index, object[keys[index]], object) === false) { return; } } } each(arr, (i, v) => arrRes.push(v)); each(obj, (i, v) => objRes.push(v)); console.log(arrRes, objRes);

You can also make a simple loop when having a very specific task, but the type of the object is unknown, like this:

for (const [key, val] of Object.entries(ArrayOrObject)) {
  // key: the current key or index
  // val: obj[key] value
  /* Do what you need here */
}

If your loop needs a (conditionally) early break, you can use break keyword to brake the loop. See Object.entries for more information.

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