替换过滤数据中的值



我有这个数组。

filteredData = [ {roles: 1,2,3,4},
{roles: 4,3,2,1} ]
role = [ {role_id: 1, role_name: User},
{role_id: 2, role_name: Coach},
{role_id: 3, role_name: Admin},
{role_id: 4, role_name: Participator} ]

如何根据role_idfilteredData中的roles改为role_name?

请看下面的代码片段:

new Vue({
el: '#demo',
data() {
return {
email: null,
filteredData: [{ind_id: 1, first_name: "aaa", last_name: "bbb", email: "aa@bb.com", roles: [1,2]}, {ind_id: 2, first_name: "ccc", last_name: "ddd", email: "cc@bb.com", roles: [2, 3, 4]}],
roles: [{role_id: 1, role_name: "Participant"}, {role_id: 2, role_name: "Coach"}, {role_id: 3, role_name: "Admin"}, {role_id: 4, role_name: "User"}]
}
},
methods: {
// 👇 use map and find to extract role names
getRoles(r) {
return r.map(r => r.name = this.roles.find(f => f.role_id === r).role_name)
},
searchResult(e) {
this.filteredData = this.fetchedData.filter((data) => {
return (
data.email.toLowerCase().includes(this.email.toLowerCase()) ||
data.first_name.toLowerCase().includes(this.email.toLowerCase()) ||
data.last_name.toLowerCase().includes(this.email.toLowerCase())
);
});
}
}
})
const filteredData = [ {roles: [1,2,3,4]},
{roles: [4,3,2,1]} ]
const role = [ {role_id: 1, role_name: 'User'},
{role_id: 2, role_name: 'Coach'},
{role_id: 3, role_name: 'Admin'},
{role_id: 4, role_name: 'Participator'} ]
const getRoles = (r) => {
return r.roles.map(r => r.name = role.find(f => f.role_id === r).role_name)
}
console.log(getRoles(filteredData[0]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<input v-model="email" id="criteria" placeholder="Search a User" class="input1" required />
<button @click="searchResult" label="Find">search</button>
<table id="table">
<tr>
<th>First name</th>
<th>Last Name</th>
<th>Email</th>
<th>Roles</th>
<th>Actions</th>
</tr>
<tr v-for="data in filteredData" :key="data.ind_id" :value="data.ind_id">
<td>{{ data.first_name }}</td>
<td>{{ data.last_name }}</td>
<td>{{ data.email }}</td>
<!-- 👇 call method and pass roles to get role names -->
<td>{{ getRoles(data.roles) }}</td>
<td>
<button @click="sendProps(data)">
Edit
<i class="fa-regular fa-edit" aria-hidden="true"></i>
</button>
</td>
</tr>
</table>
</div>

观察:filteredData中的roles不包含有效值。它应该是一个数组

我的实现方法,我将角色数组转换为key: value对对象。这样我就可以很容易地绑定role_name,同时迭代filteredData数组。

<<p>演示strong>:

const filteredData = [
{ roles: [1,2,3,4] },
{ roles: [4,3,2,1] }
];
const role = [
{role_id: 1, role_name: 'User'},
{role_id: 2, role_name: 'Coach'},
{role_id: 3, role_name: 'Admin'},
{role_id: 4, role_name: 'Participator'}
];
const roleObj = {};
role.forEach(obj => {
roleObj[obj.role_id] = obj.role_name
});
const res = filteredData.map(obj => {
return obj.roles.map(roleId => {
return roleObj[roleId]
});
});
console.log(res);

最新更新