简体   繁体   中英

JavaScript Matching one array with another?

在此处输入图片说明

above i have the picture of my arrays, below code i have mapped 2 sets of array .Purpose of this function is to make ' _polygons ' empty array. i have a rest service which is ' this.siAsset.updateComponent(_id, _polygons) ' that is designed to update each asset. only thing is, i cant seem to pass an array of data to the update component service i have, its designed to take one id and one object as a parameter (if there is a way around , please provide) as you can see by the picture, both _id and _polygons have arrays of id's an arrays of objects. Question is, how can i loop and match to call the rest to go through each id and object instead of calling by writing the code 9 times like this.siAsset.updateComponent(_id[0], _polygons[0]) ...this.siAsset.updateComponent(_id[9], _polygons[9])

  deleteAllZones = () => { let assetVal = this.asset.$$state.value console.log('tenant', assetVal) let _polygons = assetVal.map(function (a) { a.polygon = [] return a }) console.log('a',_polygons) let _id = assetVal.map(function (a) { let id = a.id return id }) console.log('id',_id) let message = this.$filter('translate')('SI-MESSAGES.DELZONE-MSG'); let title = this.$filter('translate')('SUBHEADER.DELZONE-TITLE'); let button = this.$filter('translate')('BUTTON.DELETE'); this.siAlertDialog.confirm(message, title, button) .then(() => { this.siAsset.updateComponent(_id, _polygons).then(() => { this.toastIt.simple(this.$filter('translate')('SI-MESSAGES.ZONE-DELETED')) }, (err) => { this.siAlertDialog.error(); } ) }) } 

Your code snippet doesn't work. I've made dummy entries. This should give you an idea. Basically, you need to loop over one array and use the index to find corresponding items in the second

 // Mocking data here let assetVal = [{ id: 1 }, { id: 2 }, { id: 3 } ] let _polygons = assetVal.map(function(a) { a.polygon = [] return a }) //console.log('a', _polygons) let _id = assetVal.map(function(a) { let id = a.id return id }) //console.log('id', _id) // Mocking done let updateComponent = (id, polygon) => { return new Promise((resolve, reject) => { resolve({ id, polygon }) }) } _id.forEach((id, i) => { updateComponent(id, _polygons[i]).then(result => { console.log(result) }) }) 

Also, by looking at your code, it doesn't look like your updateComponent method needs id to be passed as a parameter as it is already present in the polygon as well. Maybe you want to refactor that.

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