我获取所有库存的json数据是
{
"status": true,
"data": [
{ "inv_id": 1, "name": "Arts" },
{ "inv_id": 2, "name": "web" },
{ "inv_id": 3, "name": "mobileapp" },
{ "inv_id": 4, "name": "ws" },
{ "inv_id": 5, "name": "aop" },
{ "inv_id": 6, "name": "bin" },
{ "inv_id": 7, "name": "webs" },
{ "inv_id": 8, "name": "hell" }
]
}
用户已选择的我的json数据将采用以下格式
{
"data": {
"pid": 109,
"contact": {
"email": "ew98@gmail.com",
"phone": 85998472,
"address": { "country": "India", "state": "Kerala" }
},
"about": "hello how are you",
"is_featured": false,
"avg_rating": 0,
"total_reviews": 0,
"reviews": [],
"inventory": [
{
"item": {
"name": "Arts",
"category": { "name": "Education", "id": 1 },
"id": 1
}
}
],
"review": null
},
"status": true
}
这里已经选择了arts,所以当我提供编辑选项时,我需要避免使用相同的选项。我怎样才能达到同样目的。
mounted() {
var self = this
data = {}
data["auth-token"] = this.authType
data["pid"] = this.pid
$.ajax({
url: "http://127.0.0.1:8000/get/post/",
data: data,
type: "POST",
dataType: "json",
success: function(e) {
if (e.status == 1) {
self.inventory = e.data.inventory
data = {}
data["category"] = self.catid
data["cat_id"] = self.catid
$.ajax({
url: "http://127.0.0.1:8000/alpha/get/inventory/",
data: data,
type: "POST",
dataType: "JSON",
success: function(e) {
if (e.status == 1) {
self.inventoryall = e.data
}
},
})
}
},
})
}
我在库存[]中已经存储了库存[]和库存中的所有库存。
我的HTML代码是
<div class="form-group">
<label>Inventory
<small>(required)</small>
</label>
<select
id="basic"
class="selectpicker"
data-live-search="true"
data-live-search-style="begins"
title="Select Your Subcategory"
v-model="inv" name="inv[]" multiple required="required"
>
<option v-for="sop in inventoryall" v-bind:value="sop.inv_id">{{sop.name}}</option>
</select>
</div>
所以,当我在这里显示库存时,我需要避免已经选择过的库存。请帮我解决一下。
答案 0 :(得分:2)
您可以在此处使用数组filter
方法:
// filter loops through every item in the array and returns a new array
// if the filter function returns true, the item stays in the new array
// if the filter function returns false, the item is removed
self.inventoryall = self.inventoryall.filter(item => {
// loop through all of the currently selected items
for (const selectedItem of self.inventory) {
// if we find a current item with the same ID as the selected one,
// return false, so we don't keep the item
if (selectedItem.id === item.inv_id) {
return false
}
}
// if we never find an item with a matching ID, return true to keep it
return true
})
请注意,此方法仅适用于支持ES6的浏览器,因此如果您需要支持较旧的浏览器,请在MDN页面上使用polyfill。
另一个注意事项,因为您正在使用Vue,这可能是computed property的一个很好的用例。