I have an array of objects, each object has a list of id, like this:
objects: [
{
ids: [1,2],
name: 'alpha'
},
{
ids: [2,3],
name: 'bravo'
}
]
I want to list them all down, like for each single id, which is 1, 2 or 3, I list all the objects contains that id in its ids
property, and create a property called id
for each listed object to hold that single id, like this:
single id array: [1, 2, 3]
id = 1 => [alpha (id = 1)]
id = 2 => [alpha (id = 2), bravo (id = 2)]
id = 3 => [bravo (id = 3)]
But when I run it, all listed objects gets only the last id in their ids
which is 2 or 3 only, although I looped through the single id array 1, 2, 3
and assigned each of the id.
single id array: [1, 2, 3]
id = 1 => [alpha (id = 2)]
id = 2 => [alpha (id = 2), bravo (id = 3)]
id = 3 => [bravo (id = 3)]
Here is an example:
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
listData: [
{
ids: [1,2],
name: 'alpha'
},
{
ids: [1,2],
name: 'bravo'
},
{
ids: [1,2,3],
name: 'gamma'
},
{
ids: [3,4],
name: 'delta'
}
],
detailData: []
},
created() {
var ids = [];
this.listData.forEach(data => {
data.ids.forEach(id => {
if(!ids.includes(id)) ids.push(id);
})
})
ids.forEach(id => {
this.listData.forEach(data => {
if(data.ids.includes(id)) {
var obj = data;
obj.id = id;
this.detailData.push(obj);
}
})
})
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr v-for="(data, idx) in detailData">
<td>{{ data.id }}</td>
<td>{{ data.name }}</td>
</tr>
</tbody>
</table>
</div>
I don't know why or how this happened. Hope you guys can find out the problem and explain this for me. Thanks a lot!
Sorry for my bad English.