Перебор данных полученных сервера axios во vue js
Всем доброго дня, у меня возникла следующая проблема. Я перешел на vue js и пытаюсь выдать отсортированные данные в combobox шаблона vuetifyjs.
Я получаю данные с сервера (использую axios). Данные следующего типа.
{
"data": {
"status": 0,
"response": [
{
"id": "m",
"desc": "Ст 1",
"nodes": [
{
"id": "A",
"role": "AB",
"desc": "Бака 1",
"url": "http://1927"
},
{
"id": "A2",
"role": "AB",
"desc": "Ба 2",
"url": "http://1927"
},
{
"id": "RB",
"role": "RB",
"desc": "БО",
"url": "http://1927"
},
{
"id": "M1",
"role": "MЧ",
"desc": "MЧ 1",
"url": "http://1927"
},
{
"id": "M2",
"role": "MЧ",
"desc": "MЧ 2",
"url": "http://1927"
}
]
},
{
"id": "d",
"desc": "Ст",
"nodes": [
{
"id": "A1",
"role": "AB",
"desc": "Ба 1",
"url": "http://1927"
},
{
"id": "A2",
"role": "ABS",
"desc": "Бака 2",
"url": "http://1927"
},
{
"id": "RB",
"role": "RB",
"desc": "РБ",
"url": "http://1927"
},
{
"id": "MЧ",
"role": "MЧ",
"desc": "MЧ",
"url": "http://1927"
}
]
}
]
}
Лишний кусок я убрал, работаю именно с этим.
Далее я сформировал комобобокс и сделал пару запросов для проверки, что с сервера все приходит.
<template>
<div id="app">
<v-container fluid>
<v-row align="center">
<v-col cols="12" sm="6">
</v-col>
<v-col cols="12" sm="6">
<v-select
:items="array.data.response[0].nodes[0]"
label="Select"
multiple
hint="Pick your favorite states"
persistent-hint
></v-select>
</v-col>
</v-row>
</v-container>
{{ array }}
<hr>
{{ array.data.response[0].nodes }}
<hr>
<div v-for="i in even(array.data.response[0].nodes)" class="item" :key="i">
{{i.url}}
</div>
<hr>
</div>
</template>
Далее получаем следующий скрипт
<script>
import axios from 'axios'
import { cURL } from '@/utils/static-date'
let nodess = {"id": ""};
let configuration = 'getg';
export default {
data: () => ({
array: [],
computed: {
},
}),
mounted() {
axios.post(cURL,
{
request_type: configuration,
request: nodess
},
{ 'Content-Type': '/app/json' })
.then(response => (this.array = response))
.catch(error => console.log(error))
},
methods: {
even: function(arr) {
// Set slice() to avoid to generate an infinite loop!
return arr.slice().sort(function(a, b) {
return a.id - b.id;
});
}
},
};
</script>
Что в итоге я пытаюсь получить. Мне необходимо взять из массива m
"id": "m",
"desc": "Ст 1",
"nodes": [.....]
и вытащить только Id. Положить в массив и передать в комобокс. Вместо :items="array.data.response[0].nodes[0]" поставить :items="arrayId" например и передать все id. Там срабатывает только один. Без использование v-for и так далее
Я понимаю что необходимо сделать это следующим способом, например
var array = [];
var index, len;
for (index = 0, len = array.data.response[0].nodes.length; index < len; ++index) {
console.log(array.data.response[0].nodes[index]);
}
Подскажите, как данные сортировки реализуются именно в проекте vue js. Заранее спасибо за любой ответ и извините, если вопрос слишком тупой.
Ответы (1 шт):
Получил ответ от Eugene Kuznetsov. Спасибо, ему. Подправил код под данный вопрос. Единственное пока думаю, как сделать передачу именное через массив arr, а не по наименование функции (test)
SortIdMnode:function () {
const arrId = [];
const keys = Object.keys(this.array.data.response);
const values = Object.values(this.array.data.response);
for (let i = 0; i < keys.length; i += 1) {
if (values[i].id === 'mnode') {
for (let node = 0; node < values[i].nodes.length; node += 1) {
arrId.push(values[i].nodes[node].id);
}
}
}
return arrId;
},