I have a this code that fetches data from a remote server and i have placed it on mounted
var get_one = 'https://api.example.com/rb.php';
axios.get(get_one)
.then(response => {
// console.log(response.data);
var data = response.data;
this.roomsData = data;
this.room_name = response.data.room_name;
this.roomsData.room_photos = response.data.room_photos;
})
.catch(e => {
this.errors.push(e)
});
when i refresh the page and {{roomsData.room_photos}} looks like this
[ { "url": "/var/www/html/uploads/609cd3aaaaefd.jpg" }, { "url": "/var/www/html/uploads/609cd3aaa9dc2.jpg" }, { "url": "/var/www/html/uploads/609cd3aab1252.jpg" }, { "url": "/var/www/html/uploads/609cd3aab147a.jpg" }, { "url": "/var/www/html/uploads/609cd3aab0226.jpg" }, { "url": "/var/www/html/uploads/609cd3aaaf92b.jpg" }, { "url": "/var/www/html/uploads/609cd3aaec480.jpg" }, { "url": "/var/www/html/uploads/609cd3ab3a61b.jpg" }, { "url": "/var/www/html/uploads/609cd3ab432cb.jpg" }, { "url": "/var/www/html/uploads/609cd3ab00b91.jpg" }, { "url": "/var/www/html/uploads/609cd3ab02040.jpg" }, { "url": "/var/www/html/uploads/609cd3ab43f3e.jpg" }, { "url": "/var/www/html/uploads/609cd3ab3a634.jpg" }, { "url": "/var/www/html/uploads/609cd3ab4729f.jpg" }, { "url": "/var/www/html/uploads/609cd3ab47168.jpg" }, { "url": "/var/www/html/uploads/609cd3ab7af65.jpg" }, { "url": "/var/www/html/uploads/609cd3ab7dae1.jpg" }, { "url": "/var/www/html/uploads/609cd3ab8738f.jpg" }, { "url": "/var/www/html/uploads/609cd3ab86f15.jpg" }, { "url": "/var/www/html/uploads/609cd3ab8af48.jpg" }, { "url": "/var/www/html/uploads/609cd3ab95423.jpg" }, { "url": "/var/www/html/uploads/609cd3abbbdf9.jpg" }, { "url": "/var/www/html/uploads/609cd3abc455e.jpg" }, { "url": "/var/www/html/uploads/609cd3abca83e.jpg" }, { "url": "/var/www/html/uploads/609cd3abca0a0.jpg" }, { "url": "/var/www/html/uploads/609cd3abcfa7a.jpg" }, { "url": "/var/www/html/uploads/609cd3abd9d73.jpg" }, { "url": "/var/www/html/uploads/609cd3ac09a00.jpg" }, { "url": "/var/www/html/uploads/609cd3ac1382f.jpg" } ]
This is my computed function
computed: {
image_viewer_data: function () {
let vd = this.roomsData.room_photos
console.log('inside computed',vd)
let modifiedArr = vd.map(function(item){
let url_parts = item.url.split('/')
return 'https://api.example.com/uploads' + '/' + url_parts[url_parts.length - 1]
});
return modifiedArr;
}
},
which produces data in the following format when i {{image_viewer_data}}
[ "https://api.example.com/uploads/609cd3aaaaefd.jpg", "https://api.example.com/uploads/609cd3aaa9dc2.jpg", "https://api.example.com/uploads/609cd3aab1252.jpg", "https://api.example.com/uploads/609cd3aab147a.jpg", "https://api.example.com/uploads/609cd3aab0226.jpg", "https://api.example.com/uploads/609cd3aaaf92b.jpg", "https://api.example.com/uploads/609cd3aaec480.jpg", "https://api.example.com/uploads/609cd3ab3a61b.jpg", "https://api.example.com/uploads/609cd3ab432cb.jpg", "https://api.example.com/uploads/609cd3ab00b91.jpg", "https://api.example.com/uploads/609cd3ab02040.jpg", "https://api.example.com/uploads/609cd3ab43f3e.jpg", "https://api.example.com/uploads/609cd3ab3a634.jpg", "https://api.example.com/uploads/609cd3ab4729f.jpg", "https://api.example.com/uploads/609cd3ab47168.jpg", "https://api.example.com/uploads/609cd3ab7af65.jpg", "https://api.example.com/uploads/609cd3ab7dae1.jpg", "https://api.example.com/uploads/609cd3ab8738f.jpg", "https://api.example.com/uploads/609cd3ab86f15.jpg", "https://api.example.com/uploads/609cd3ab8af48.jpg", "https://api.example.com/uploads/609cd3ab95423.jpg", "https://api.example.com/uploads/609cd3abbbdf9.jpg", "https://api.example.com/uploads/609cd3abc455e.jpg", "https://api.example.com/uploads/609cd3abca83e.jpg", "https://api.example.com/uploads/609cd3abca0a0.jpg", "https://api.example.com/uploads/609cd3abcfa7a.jpg", "https://api.example.com/uploads/609cd3abd9d73.jpg", "https://api.example.com/uploads/609cd3ac09a00.jpg", "https://api.example.com/uploads/609cd3ac1382f.jpg" ]
This is how i am using my computed function
<div class="carousel-item" v-for="(value,index) in image_viewer_data" >
<img class="d-block w-100" :src="value" :id="index" >
</div>
when i refresh the page i get this errors.
[Vue warn]: Error in render: "TypeError: vd.map is not a function
and
TypeError: vd.map is not a function
Why is the code simultaneously working and failing at the same time.
that warning message means that vd is not an array , thus cannot find map() . and its working because the type of object you have is iterable so it behaved like an array.
try creating a new array instance from it using Array.from() :
let vd = [ { "url": "/var/www/html/uploads/609cd3aaaaefd.jpg" }, { "url": "/var/www/html/uploads/609cd3aaa9dc2.jpg" }, { "url": "/var/www/html/uploads/609cd3aab1252.jpg" }, { "url": "/var/www/html/uploads/609cd3aab147a.jpg" } ]
let modifiedArr = Array.from(vd).map(function(item){
let url_parts = item.url.split('/');
return 'https://api.example.com/uploads' + '/' + url_parts[url_parts.length - 1];
});
console.log(modifiedArr);
seems like the vd is not an array while you getting errors. Wondering why? The possible reason, your code is accessing the vd.map before the data loads.
So, adding a null check before accessing vd will help here. Eg:
let modifiedArr = vd?.map(item=>{
...
...
}) || [];
will be a perfect blend here.
In common format,
let modifiedArr = vd && vd.map() || []
Related
I am desperately trying to generate multiple select inputs for a given JSON from an Backend but I cant make it work. The JSON response I am getting looks smth like this:
{
"selectData": [
{
"id": "ats_2323680",
"label": "Follow up",
"value": "option_id_1"
},
{
"id": "ats_2323701",
"label": "1st Interview, Client",
"value": "option_id_1"
},...
],
"optionData": {
"texts": [
"Sourced",
"On hold",
...
],
"values": [
"option_id_1",
"option_id_2",
]
}
}
Ive already tried several ways and my last attempt looks like this:
Template:
<div v-for="select in selectData" :key="select.id">
<p>{{ select.label }}</p>
<v-select
:items="optionData.texts"
:value="getOptionById(select.value)"
#input="(id) => updateSelect(select, id)"
></v-select>
</div>
Script:
<script>
export default {
data() {
return {
selectData: [],
optionData: {
values: [],
texts: [],
},
};
},
methods: {
fetchData() {
const headers = this.authorizationHeader;
axios
.get(url,
{
headers,
}
)
.then((response) => {
let data = response.data;
this.selectData = data.selectData;
this.optionData = data.optionData;
})
.catch((error) => console.log(error));
},
updateSelect(select, id) {
select.value = id;
},
getOptionById(id) {
let i = this.optionData.values.findIndex((x) => x === id);
return this.optionData.texts[i];
},
},
mounted() {
this.fetchData();
},
};
</script>
I am also not super happy with the JSON struct I am getting. The reason that the optionTextId is also send is, that the optionTexts will be in different languages.
I am really happy with any advise.
I think I solved it. I think it was a classy case of overthinking.
First I changed the JSON structure in the backend like:
{
"selectData": [
{
"id": "ats_2323680",
"label": "Follow up",
"text": "Sourced",
},
{
"id": "ats_2323701",
"label": "1st Interview, Client",
"text": "Kandidaten nachgefasst",
},
...
],
"optionData": {
"texts": [
"Sourced",
"Kandidaten kontaktiert",
...
],
"values": [
"option_id_1",
"option_id_2",
...
]
}
}
Then I changed the Vue code to:
Template:
<div v-for="select in selectData" :key="select.id">
<label for="location">{{ select.label }}</label>
<select id="location" name="location" v-model="select.text">
<option
v-for="option in optionData.texts"
:key="option"
:value="option"
>
{{ option }}
</option>
</select>
</div>
Script:
<script>
export default {
data() {
return {
selectData: [],
optionData: {
values: [],
texts: [],
},
};
},
methods: {
fetchData() {
const headers = this.authorizationHeader;
axios
.get(
url,
{
headers,
}
)
.then((response) => {
let data = response.data;
this.selectData = data.selectData;
this.optionData = data.optionData;
})
.catch((error) => console.log(error));
},
},
mounted() {
this.fetchData();
},
};
</script>
Apparently changing the JSON struc and using v-model did the magic. Might be obvious. Hope this helps a lost soul like me at some point :)
I am developing of a SAPUI5 application, in my application I need to pass data from one View1 to View2. I follow some sample code from internet but it seems like does not work for me.
The following is my source code
View1.controller.js
onShoppingCartPressed: function(){
var viewCartData = {
"Customer" : SelectedCustomer,
"Salesman" : SelectedSalesman,
"TxnKey" : "TXN1000103"
};
this._oRouter.navTo("ViewCarts", viewCartData);
}
View2.controller.js
onInit: function () {
this._oRouter.getRoute("ViewCarts")
.attachMatched(this._onRouteMatched, this);
},
_onRouteMatched: function(oEvent) {
console.log(oEvent.getParameter("arguments"));
},
Manifest.json
"routing": {
"config": {
"routerClass": "sap.f.routing.Router",
"viewType": "XML",
"viewPath": "com.accenture.newspage.order.ui.order-ui.view",
"controlId": "flexibleColumnLayout",
"transition": "slide",
"controlAggregation": "beginColumnPages",
"bypassed": {
"target": [
"notFound"
]
},
"async": true
},
"routes": [
{
"pattern": "orderDetail/{order}/{layout}",
"name": "orderDetail",
"target": [
"order",
"orderDetail"
]
},
{
"pattern": "ViewCarts",
"name": "ViewCarts",
"target": "viewCarts"
}
],
"targets": {
"worklist": {
"viewName": "Worklist",
"viewId": "worklist",
"viewLevel": 1
},
"viewCarts": {
"viewName": "ViewCart",
"viewId": "ViewCartPage",
"viewLevel": 1
}
}
}
When I console.log() out the data, it shows me empty data and it does not show the data that I passed from View1.
You seem to have two options here in my option. Correct me if I'm wrong.
Hope this helps.
Option 1
Manifest
{
"pattern": "ViewCarts/customer/{Customer}/Salesman/{Salesman}/key/{TxnKey}",
"name": "ViewCarts",
"target": "ViewCarts"
}
Sending controller
onShoppingCartPressed: function(oEvent) {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("viewCarts", {
Customer: "XXXXXXXXXXXX", // can't be an object
Salesman: "xxxxxxxxxxxx",
TxnKey : "TXN1000103"
});
}
Receiving controller
onInit: function() {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.getRoute("viewCarts").attachMatched(this._onRouteMatched, this);
},
_onRouteMatched: function(oEvent) {
var customer = oEvent.getParameter("arguments").Customer;
var salesman = oEvent.getParameter("arguments").Salesman;
var key = oEvent.getParameter("arguments").TxnKey;
}
Option 2
Manifest
No changes from yours
Sending controller
onShoppingCartPressed: function(oEvent) {
var viewCartData = {
"Customer": "XXXXXXXXXXXX",
"Salesman": "xxxxxxxxxxxx",
"TxnKey": "TXN1000103"
};
var oModel = new sap.ui.model.json.JSONModel(viewCartData);
this.getOwnerComponent().setModel(oModel, "viewCartData");
// OR sap.ui.getCore().setModel(oModel, "viewCartData");
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("viewCarts");
}
Receiving controller
onInit: function() {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.getRoute("viewCarts").attachMatched(this._onRouteMatched, this);
},
_onRouteMatched: function(oEvent) {
var oModel = this.getView().getModel("viewCartData");
// OR var oModel = sap.ui.getCore().getModel("viewCartData");
}
For me in most scenarios it's better to use sessionStorage.
It allows you to save almost anything (also javascript Object) and access it anywhere in webapp.
sessionStorage.setItem('myKeyString', 'myString'); //Set value
sessionStorage.getItem('myKeyString'); // Get saved string
sessionStorage.setItem('myObject', JSON.stringify({"key": "value"})); // Save object
JSON.parse(sessionStorage.getItem('myObject')); // Get saved object
I am trying to sort a JSON array from JSON file a.json.
The array is coming like this:
{"data":
[
{"exception":"",
"name":"Data Server1",
"alias":"TOR-Server",
"delayed":"NO",
},
{"exception":"",
"name":"Data Server2",
"alias":"FRA-Server",
"delayed":"NO",
}
]
I need to sort the data by the "alias name", coming from the JSON file with Vue JS.
This is my Javascript Code for the display in Vue JS
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
json: null
},
computed: {
sorted: function() {
setTimeout(function() {
var app = this.app.json
if (app.length >= 6)
return app;
}, 5000);
}
},
methods: {
toggleClass(){
if (this.failed == true){
this.failed = false;
}
else
{
this.failed = true;
}
}
}
But the Sorted function is not working and if I try to display the servers in the sorted array, I receive a blank page.
And my for loop in the HTML page is:
<div class="mainbutton" v-for="(server, index) in json.data ">
Hope this makes sense and I could get it working.
You can use Array.sort inside a computed, to return the sorted array.
For example, to sort the array's items by name property, you can call: this.json.sort((t1,t2) => t1.name < t2.name ? -1 : 1).
Here's a working snippet:
var app = new Vue({
el: '#app',
data: {
json: [
{
"exception": "",
"name": "Data Server3",
"alias": "TOR-Server",
"delayed": "NO",
},
{
"exception": "",
"name": "Data Server1",
"alias": "TOR-Server",
"delayed": "NO",
},
{
"exception": "",
"name": "Data Server2",
"alias": "FRA-Server",
"delayed": "NO",
}
]
},
computed: {
sortedJson: function() {
return this.json.sort((t1,t2) => t1.name < t2.name ? -1 : 1);
},
sorted: function() {
setTimeout(function() {
var app = this.app.json
if (app.length >= 6)
return app;
}, 5000);
}
},
methods: {
toggleClass() {
if (this.failed == true) {
this.failed = false;
} else {
this.failed = true;
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
<div class="mainbutton" v-for="(server, index) in sortedJson ">
{{server.name }}
</div>
</div>
I'm struggling to manipulating a tree object in JS, it might be simple but I can't find out.
Here is the object :
{
"100-silk": {
"url": "https://www.striiiipes.com/product-category/100-silk/"
},
"apparel": {
"url": "https://www.striiiipes.com/product-category/apparel/"
},
"ipad-accessories": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/",
"ipad-air": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-air/"
},
"ipad-mini": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-mini/"
},
"ipad-pro": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/",
"ipad-pro-12-9": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/ipad-pro-12-9/"
},
"ipad-pro-9-7": {
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/ipad-pro-9-7/"
}
}
}
I'm using a simple recursion function to get throught all childrens :
function parseCategories(a) {
if (typeof a === 'object') {
$.each(a, function (i, v) {
//if we only have a "url" object, then we're on last branch and can parse it
if (Object.keys(v).length === 1 && 'url' in v) {
//dosomething
} else { // then we need to go deeper in the tree
parseCategories(v);
}
})
}
}
I'd like to use this function to also save the breadcrumb and get an object like this :
"100-silk": {
"categories" : ["100-silk"],
"url": "https://www.striiiipes.com/product-category/100-silk/"
},
"apparel": {
"categories" : ["apparel"],
"url": "https://www.striiiipes.com/product-category/apparel/"
},
"ipad-accessories": {
"categories" : ["ipad-accessories"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/",
"ipad-air": {
"categories" : ["ipad-accessories", "ipad-air"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-air/"
},
"ipad-mini": {
"categories" : ["ipad-accessories", "ipad-mini"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-mini/"
},
"ipad-pro": {
"categories" : ["ipad-accessories", "ipad-pro"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/",
"ipad-pro-12-9": {
"categories" : ["ipad-accessories", "ipad-pro", "ipad-pro-12-9"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/ipad-pro-12-9/"
},
"ipad-pro-9-7": {
"categories" : ["ipad-accessories", "ipad-pro", "ipad-pro-9-7"],
"url": "https://www.striiiipes.com/product-category/ipad-accessories/ipad-pro/ipad-pro-9-7/"
}
}
}
};
So the point is to save the full breadcrumb in each child and parent. How should I change the parsing function to get this object ? I've tried to pass also the parent in each loop but I can't manage to get exactly what I want...
I've create a jsfiddle here.
Thanks a lot for your help !
You could check the properties for nested objects and assign the category value.
It works with a check, if
object[k] is a truthy value, and
typeof object[k] === 'object', if the type is an object, and
!Array.isArray(object[k]), if the actual property is not an array, like a new added category,
then it assigns a new property category by using the category from the level before and adding the actual key to it.
function updateCategory(object) {
Object.keys(object).forEach(function (k) {
if (object[k] && typeof object[k] === 'object' && !Array.isArray(object[k])) {
object[k].category = (object.category || []).concat(k);
updateCategory(object[k]);
}
});
}
var data = { "100-silk": { url: "URL/100-silk/" }, apparel: { url: "URL/apparel/" }, "ipad-accessories": { url: "URL/ipad-accessories/", "ipad-air": { url: "URL/ipad-accessories/ipad-air/" }, "ipad-mini": { url: "URL/ipad-accessories/ipad-mini/" }, "ipad-pro": { url: "URL/ipad-accessories/ipad-pro/", "ipad-pro-12-9": { url: "URL/ipad-accessories/ipad-pro/ipad-pro-12-9/" }, "ipad-pro-9-7": { url: "URL/ipad-accessories/ipad-pro/ipad-pro-9-7/" } } } };
updateCategory(data);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
What am I doing wrong with my bindings? I simply get [object HTMLElement] returned for each one.
Please note this is a pared-down version and I will be wanting to access the full range of the JSON values.
Fiddle:
https://jsfiddle.net/0416f0s7/2/
Code:
<div data-bind="text: intro"></div>
function ViewModel(stories) {
var self = this;
self.stories = ko.observableArray(ko.utils.arrayMap(stories, function(story) {
return story.stories;
}));
};
$.getJSON('data.json', function(data) {
window.storyViewModel = new ViewModel(data.stories);
ko.applyBindings(window.storyViewModel);
});
JSON (filename data.json):
{
"stories": [
{
"intro": "Hi",
"outro": "Bye",
"elements": [
{
"title": "Title 1",
"image": "img/image1.jpg",
"paragraph": "Wordswordswords"
},
{
"title": "Title 2",
"image": "img/image2.jpg",
"paragraph": "More wordswordswords"
}
]
}
]
}
Your html change to
`<div data-bind="foreach:stories">
<div data-bind="text: intro"></div>
</div>
your code change to
function test(stories) {
var self = this;
self.stories = ko.observableArray(ko.utils.arrayMap(stories, function (story) {
return story;
}));
}