Use Split in Vue js inside a loop - javascript

I have an api calling data from db, one of column has Image file name stored. I want to split the file and get the last 3 letters of each filename after the DOT. I am stuck here:
axios.get('/api/v1/chats/messages/' + this.chat).then(response => {
this.result = response.data;
this.details = this.result.data;
for (var j = 0; j < this.details.length; j++) {
this.str = this.details[j].image;
this.details[j].image_type = this.str.split(".");
}
console.log(this.details)
})
.catch(error => {
toastr.error('Something went wrong', 'Error', {
positionClass: 'toast-bottom-right'
});
this.cancelAutoUpdate();
});
Would really appreciate if someone could help me OR please let me know if theres any other way to get the file extension in vue js. Thanks :)

function split splits a string into an array by a separator. You got an array, but forgot to get the array element you are interested in.
You need to replace this.str.split("."); to this.str.split(".")[1]
const details = [
{
image: 'image1.jpg',
},
{
image: 'image2.png',
},
{
image: 'image3.gif',
}
]
for (let detail of details) {
let str = detail.image;
detail.image_type = str.split(".")[1];
}
console.log(details)

Related

Why split after new line is not returning single array using JavaScript?

I have a string text after fetching an API with a for loop, that returns me a list of names, each name separated by a new line. When I use the code in the snippet, it returns me each name in an individual array, instead of a single array. Is there anything wrong with the RegEx? Could someone please tell me what is wrong? Thank you very much for the help.
function loadMagicItems() {
fetch('https://api.open5e.com/magicitems/?fields=slug,name,desc,type,rarity&limit=1000'
).then(function (responses) {
return responses.json();
}).then(function (data) {
displayMagicItems(data);
});
};
function displayMagicItems(data) {
for (let i = 0; i < data.results.length; i++) {
const magicItemsName = data.results[i].name.split(/\n/);
console.log(magicItemsName);
};
};
<body onload="loadMagicItems()">
</body>
Your JSON data is an array of items. Not all items as one string seperated by a newline character.
The easiest way to get the names of the items, is to use a map and return the name of the item.
function loadMagicItems() {
fetch('https://api.open5e.com/magicitems/?fields=slug,name,desc,type,rarity&limit=1000').then(function(responses) {
return responses.json();
}).then(function(data) {
displayMagicItems(data.results);
});
};
function displayMagicItems(items) {
items = items.map(({name}) => name);
console.log(items);
};
<body onload="loadMagicItems()" />
Your regex is correct, this is behavior expected. For each name string you generating an array spllited by \n. If you want join the results you can do:
function displayMagicItems(data) {
const singleArrayWithNames = []
for (let i = 0; i < data.results.length; i++) {
const magicItemsName = data.results[i].name.split(/\n/);
singleArrayWithNames.push(...magicItemsName) // pushing names extracted to new array
};
console.log("all names: ", singleArrayWithNames)
};
Since the name property is already seperated, and your'e using .split
each iteration, it's creating a new array each time.
function loadMagicItems() {
fetch('https://api.open5e.com/magicitems/?fields=slug,name,desc,type,rarity&limit=1000'
).then(function (responses) {
return responses.json();
}).then(function (data) {
displayMagicItems(data);
});
};
function displayMagicItems(data) {
const magicItemsName=[]
for (let i = 0; i < data.results.length; i++) {
magicItemsName[i] = data.results[i].name;
};
console.log(magicItemsName);
};
<body onload="loadMagicItems()">
</body>

How do I console.log json information?

quite new to working with both api's and javascript. I'm trying to console.log out the amount of times a friend of mine has died in rust, but all items are named "name:" An img of what I mean:
I'm using axios to call the api, here's the code:
var statsApi = 'http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?';
var statsAppId = 'appid='+252490+'&'
var statsSteamApiKey = 'key='+process.env.STEAM_API+'&';
var statsUserArg = 'steamid='+userID;
var steamStatsApi = statsApi + statsAppId + statsSteamApiKey + statsUserArg;
axios
.get(steamStatsApi)
.then((res) =>{
message.channel.send("AAAA");
// console.log(res['data']['playerstats']['stats']['name' == 'deaths']);
for(re in res['data']['playerstats']['stats']) {
if(re['name'] === 'deaths') {
console.log('test');
console.log(re['value']);
}
else {
console.log('Fel');
}
}
})
.catch((err) => {
console.error('Error:', err);
})
Again if anyone knows how to get the amount of 'deaths' I'd be super grateful.
Turns out it was quite easy, if anyone has this problem just use the following code which I am about to provide:
var index = -1;
for(var i = 0; i < Object.keys(res['data']['playerstats']['stats']).length; i++) {
if(res['data']['playerstats']['stats'][i]['name'] === 'deaths') {
index = i;
var userDeaths = res['data']['playerstats']['stats'][index]['value'];
break;
}
}
What this does is that it loops trough every object named "name:" until it finds 'deaths' in one of them. I change i to that and now i'm able to print out the value which i'm looking for.
Please check this code:
let res = [{ name: "deaths", value: 2694}, {name:"bullet_fired", value: 343328}];
let i = 0;
for(i=0;i<res.length;i++){
if(res[i].name =="deaths"){
console.log(res[i].value);
}
}
Here res variable will contain your json values.

can't get data form array

I try to get data from the array but I get undefined
please check the image of my problem
I don't know what I'm missing
please help
I have an array called nameTable of string
when I console.log(this.nameTable) I got this : check the image please
enter image description here
and when I click to arrow I got this : check image please
enter image description here
the problem is the table has 5 element I want to show them so I make for loop to do that
for (let i = 0; i < 5; i++){
console.log(this.nameTable[i])
}
but us you can see in the image I got undefined
enter image description here
here the code :
employeeL:Array<Awinjard> = [];
inv_agentTab: Array<Inv_agent> = [];
drafbiesTab: Array<Drafbies> = [];
nameemployee: string = "";
inv_agentNombre: number = 0;
matriculeTable: Array<number> = [];
nameTable:Array<string> = [];
validatationTable: Array<number> = [];
ngOnInit() {
this.folder = this.activatedRoute.snapshot.paramMap.get('id');
this.awinjard.getAwinjardMatricule().subscribe(res => {
this.inv_agentTab = res as Array<Inv_agent>
this.inv_agentTab.forEach(element => {
this.matriculeTable[this.inv_agentNombre] = element.AGENT;
this.validatationTable[this.inv_agentNombre] = element.VLD;
this.inv_agentNombre++;
this.awinjard.getAwinjardNameAr().subscribe(res2 => {
this.drafbiesTab = res2 as Array<Drafbies>
this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
this.nameTable.push(this.nameemployee);
})
});
for (let i = 0; i < 5; i++){
// here the problem I can't get the data form nameTable array
console.log(this.nameTable[i])
let awin= <Awinjard> {
matricule: this.matriculeTable[i],
fullname: this.nameTable[i],
status: true,
done: 1,
mustBeDone:40
}
this.employeeL.push(awin);
}
})
}
You have subscribed to getAwinjardNameAr and before that response, you are trying to access the nameTable array, which is why you get undefined. #raishav-hanspal's solution is right to solve your issue, but a code change can keep things straightforward. I suggest you to write that code inside your for loop inside your subscribe. Here's the alteration:
this.awinjard.getAwinjardNameAr().subscribe(res2 => {
this.drafbiesTab = res2 as Array<Drafbies>
this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
this.nameTable.push(this.nameemployee);
let awin= <Awinjard> {
matricule: this.matriculeTable[this.inv_agentNombre],
fullname: this.nameemployee,
status: true,
done: 1,
mustBeDone:40
}
this.employeeL.push(awin);
})
You can move the code where you're logging nameTable[] inside the subscribe (where you are pushing the values into nameTable[]).
A complete solution is to use complete in subscribe() -->
this.awinjard.getAwinjardNameAr().subscribe(res2 => {
this.drafbiesTab = res2 as Array<Drafbies>
this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
this.nameTable.push(this.nameemployee);
},err => {console.log(err)}, ()=> {
for (let i = 0; i < 5; i++){
// here the problem I can't get the data form nameTable array
console.log(this.nameTable[i])}})
});
You can read more on https://angular.io/guide/observables

how to set default value in case of error

I'm learning React and I'm trying to render 10 pieces of data from a specific API.
This is a function I wrote for iterating through the fetched data and taking the title and the image:
for (let i = 0; i < 10; i++) {
data.push({
title: someMethod(allData)[i].children[0].data,
image: someMethod(allData)[i].attribs.src,
});
}
I don't know why but one of the images gives me that error:
index.js:1 TypeError: Cannot read property 'attribs' of undefined
Which stops the whole rendering.
I wanted to try to put a temporary placeholder image so the rest of the images can be loaded without any errors.
I thought about adding conditions into the image line inside the loop but it didn't work for me. What's the right way to do that?
If I wasn't clear enough please comment what wasn't clear and I'll try to describe it better.
If someMethod is synchronous (based on your code sample it should be) then you can wrap your code in try...catch block like so:
for (let i = 0; i < 10; i++) {
try {
data.push({
title: someMethod(allData)[i].children[0].data,
image: someMethod(allData)[i].attribs.src,
});
} catch (err) {
data.push({
title: 'placeholder',
image: 'placeholder',
});
continue;
}
}
Here's more cleaner version of the above:
for (let i = 0; i < 10; i++) {
let title = '';
let image = '';
try {
title = someMethod(allData)[i].children[0].data;
image = someMethod(allData)[i].attribs.src;
} catch (err) {
image = 'failed to load or something';
}
data.push({title, image});
}
for (let i = 0; i < 10; i++) {
data.push({
title: someMethod(allData)[i].children[0].data,
image: someMethod(allData)[i].attribs?.src ?? defaultSrc,
});
}
docs: Optional_chaining and Nullish_coalescing_operator
You can solve the null pointer exceptions in 2 ways.
Manually check for truthy values using ? or &&
Create a simple utility function
Point 1 will solve your problem, but however if you start using it everywhere throughout your code it may not look tidy. I'd recommend to go by creating a utility function as below.
export const getSafe = (fn, defaultValue=null) => {
try {
return fn()
} catch (e) {
return defaultValue
}
}
You can then use it anywhere like..
var result = getSafe(() => object1.data.key)
You can use it for accessing any type of values to any depth. You can also pass a default value as 2nd argument if required. by default it is set as null
var resultArray = getSafe(() => array1.data.values, [])
Just remember, the 1st value should be passed as a function.
So in your case...
for (let i = 0; i < 10; i++) {
data.push({
title: getSafe(() => someMethod(allData)[i].children[0].data, "Default Title"),
image: getSafe(() => someMethod(allData)[i].attribs.src, "placehoder_img"),
});
}
Implement the map function.
The for loop will give an error at your component
In react if you need to render elements don't implement the for loop
datas.map(......)

Mapping JSON to ES6 Classes

I have our staff in a json file, and had the idea to use that data with ES6 classes. The more I work with this, the more I feel as though I may be missing something. I had this working in coffeescript as such:
fetch = require('node-fetch')
domain = 'domain.com'
apiSrc = 'api.domain.com'
slug = 'people'
class Person
constructor: (json) -> {name: #name, title: #title, school: #school, bio: #bio} = json
email: (username) ->
username.replace(/\s/, '.').toLowerCase() + '#' + domain
profile: ->
content = []
if this.name then content.push("#{#name}")
if this.title then content.push("#{#title}")
if this.school then content.push(school) for school in "#{#school}"
if this.bio then content.push("#{#bio}")
if this.name then content.push(this.email("#{#name}"))
content.join('')
fetch('http://' + apiSrc + '/' + slug + '.json')
.then((response) -> response.json())
.then((api) ->
content = []
group = []
group.push(new Person(them)) for them in api[slug]
for them, index in group
content.push(them.profile())
console.log(content.join(''))
)
But then I thought it would be even better if I could convert it to ES6. I know the use case is simple, and classes certainly aren't necessary, since I'm just using the data for templating, however, for the sake of learning, I was attempt to do this. Am I going about this the wrong way? Right now, I feel like there should be a way to return all of the "people" that I put into the Person class. However, the only way I could figure out how to do that was to run a for loop and then write it to the document.
class Person {
constructor(data) { ({name: this.name, title: this.title, school: this.school, bio: this.bio, email: email(this.name)} = data); }
email(username) {
return username.replace(/\s/, '.').toLowerCase() + '#' + location.hostname.replace(/[^\.\/\#]+\.[^\.\/]+$/, '');
}
profile() {
return `${this.name} ${this.title}`;
}
}
var apiSrc = 'api.domain.com';
var slug = 'people';
fetch(`http://${apiSrc}/${slug}.json`)
.then(function(response) { return response.json() }) // .then(response => response.json())
.then(function(api) {
var content = [];
var group = [];
for (var i = 0; i < api[slug].length; i++) { var them = api[slug][i]; new Person(them); }
for (var i = 0; index < group.length; i++) {
var them = group[i];
content.push(them.profile());
console.log(content.join(''));
}
});
My ES6 conversion actually isn't even working right now. API returns the JSON but after that it gets messed up. Any suggestions would be really helpful as I'm trying to better myself as a coder and hope this sort of example could help others learn Classes in a real use case.
You might try using the reviver parameter of JSON.parse. Here is a simplified example:
class Person {
// Destructure the JSON object into the parameters with defaults
constructor ({name, title, school=[]}) {
this.name = name
this.title = title
this.school = school
}
}
var api = JSON.parse(a, function (k,v) {
// Is this a new object being pushed into the top-level array?
if (Array.isArray(this) && v.name) {
return new Person(v)
}
return v
})
var group = api["people/administration"]

Categories

Resources