How to display images from an array in vuepress or vuejs? - javascript

I have an array which looks like below:
questions: [
{
question: "How do you say 'My Car' in Malayalam",
answers: {
a: "a) Ente Car",
b: "b) Ninte/Ningalude Car",
c: "c) Onte Car",
d: "d) Aarudeyo Car",
},
images: "#alias/vallamkali.jpg",
correctAnswer: "a",
},
{
question: "How do you say 'your Car' in Malayalam",
answers: {
a: "a) Onte Car",
b: "b) Aarudeyo Car",
c: "c) Ninte/Ningalude Car",
d: "d) Ente Car",
},
images: "#alias/il_leki.png",
correctAnswer: "c",
},
{
question: "How do you say 'our car' in Malayalam",
answers: {
a: "a) Achante Car",
b: "b) Ninte/Ningalude Car",
c: "c) Ente Car",
d: "d) Nammalude/Njangalude Car",
},
images: "#alias/isthapetta_doubt.jpg",
correctAnswer: "d",
},
],
but when I try to print using the below code
<div v-if="index < count">
<p>{{ questions[index]['question']}}</p>
<p>{{ questions[index]['images']}}</p
</div>
Only the questions are generated correctly but the images are not displayed properly, only the location gets printed as below and is highlighted in blue. Please help.

You can not display images in p tag
You need to make method or computed property (assuming images = il_leki.png):
methods: {
getImg(img) {
return require(`#alias/${img}`);
}
}
then in template call that method in img tag (instead p tag) passing img :
<img :src="getImg(questions[index]['images']) />

I didn't use the function call.
I directly used require keyword in the img tag itself and it worked.
<img :src="require(`#alias/${questions[index]['images']}`)" alt="No image here too" />
#Nikola Pavicevic - Thanks for helping me think in this direction!

Related

Javascript, filtering on object in comparison to array

I'm still learning and I had a question the other day filtering two arrays, which helped a lot for my understanding!
However now, I have a new issue as the complexity has grown a bit from being two simple arrays! Now instead, I have a array with multiple objects named animals which categorizes animals based whether they are housepets, insects or wild animals and each contains a object with their characteristics. Now I want to compare this on a simple array seen below.
Array with Object
let animals = [
{
"housePets" : [ { "name": "Cat", "food" : "Fish", "description": "Long tail, sharp claws" }, { "name": "Dog", "food" : "Biscuits", "description" : "Humans best friend" } ]
},
{
"wildAnimals" : [ { "name": "Giraffe", "food" : "Leafes", "description" : "A very long neck" }, { "name": "Lion", "food" : "Meat", "description" : "Featured in Lion King" } ]
},
{
"insects" : [ { "name": "Ladybug", "food" : "Leafes", "description" : "Red and black" }, { "name": "Spider", "food" : "Flies", "description" : "From the friendly neighbourhood" } ]
}]
Arr:
let animalsArr2 = [housePets]
I'm having a bit of trouble fully understanding on how to work with this JSON format in general. The biggest struggle for me is targeting the specific array like wildAnimals.
For example, one thing I want to do is filter the animals array based on what's inside animalsArr2 and pick a random one from the animalsarr that's not featured in animalsArr2 like "wildAnimals" and "Insects". I hope someone can give me some ideas on how to tackle this issue or if it can be tackled in a easier way.
You can use the .find() array method to return the list that you want. For example if you want to return the wild animals list:
let animals = [
{
"housePets" : [
{ "name": "Cat", "food" : "Fish", "description": "Long tail, sharp claws" },
{ "name": "Dog", "food" : "Biscuits", "description" : "Humans best friend" }
]
},
{
"wildAnimals" : [
{ "name": "Giraffe", "food" : "Leafes", "description" : "A very long neck" },
{ "name": "Lion", "food" : "Meat", "description" : "Featured in Lion King" }
]
},
{
"insects" : [
{ "name": "Ladybug", "food" : "Leafes", "description" : "Red and black" },
{ "name": "Spider", "food" : "Flies", "description" : "From the friendly neighbourhood" }
]
}
];
const wildAnimals = animals.find((item) => item.wildAnimals);
The code above basically checks which item in your array has a property called wildAnimals and returns that item. You can read more about this method Here.
Hope that helped!
I'm gonna suppose you are forced to use this format of storing data, but I feel like I have to let you know that this isn't the best way to store info like this (you will see that it is hard to work with it). Instead of having an array of objects, you could have an object of arrays like this:
let animals = {
"housePets": [{ "name": "Cat", "food": "Fish", "description": "Long tail, sharp claws" }, { "name": "Dog", "food": "Biscuits", "description": "Humans best friend" }],
"wildAnimals": [{ "name": "Giraffe", "food": "Leafes", "description": "A very long neck" }, { "name": "Lion", "food": "Meat", "description": "Featured in Lion King" }]
}
With this approach, getting all house animals would be as easy as animals.housePets.
Back to your issue tho. If you want to get all house animals from this, you will have to filter the array. To filter arrays, you have to give it a condition that the element has to pass to be stored. Here you can see that only the object with the house animals has a housePets property, so we can take advantage of that:
let house_animals = animals.filter(obj => obj.housePets)[0].housePets; // [{ "name": "Cat", "food": "Fish", "description": "Long tail, sharp claws" }, { "name": "Dog", "food": "Biscuits", "description": "Humans best friend" }]
What it does is that it takes all the objects that have the "housePets" property, takes the first one (I suppose there will always be only one) and reads the property, giving you the array of animals.
To find animals that are only in the housePets section and not in others, you can do this:
let house_animals = animals.filter(obj => obj.housePets)[0].housePets;
let wild_animals = animals.filter(obj => obj.wildAnimals)[0].wildAnimals;
let insects = animals.filter(obj => obj.insects)[0].insects;
let only_house = house_animals.filter(animal => !wild_animals.includes(animal) && !insects.includes(animal); // This checks if the animal is in the wild_animals or insects array. If it isn't, it keeps it.
You can also check this question out
Hope this helped :)
You can follow this code as a starting point. The complete example with updated data is below.
There are two key functions:
function _get(array, label): Take the array and get the names of the animals under the label category.
function _filterAndGet(mainList, filterList): Take the main list of animals, and filter out any animals that are in filter list. Then, pick a random animal from that filtered list.
Code
const animals = [
{
housePets : [{name: 'Cat', food : 'Fish', description: 'Long tail, sharp claws'}, {name: 'Dog', food : 'Biscuits', description : 'Humans best friend'}]
},
{
wildAnimals : [{name: 'Giraffe', food : 'Leafes', description : 'A very long neck'}, {name: 'Lion', food : 'Meat', description : 'Featured in Lion King'}, {name: 'Cat', food : 'Fish', description: 'Long tail, sharp claws'}, {name: 'Ladybug', food : 'Leafes', description : 'Red and black'}]
},
{
insects : [{name: 'Ladybug', food : 'Leafes', description : 'Red and black'}, {name: 'Spider', food : 'Flies', description : 'From the friendly neighbourhood'}]
}]
const wildAnimals = _get(animals, 'wildAnimals');
console.log(`Wild animals: ${JSON.stringify(wildAnimals)}`);
const housePetsAndInsects = _get(animals, 'housePets').concat(_get(animals, 'insects'));
console.log(`House Pets and Insects: ${housePetsAndInsects}`);
console.log(`Random wild animal not in housePets and insects: ${_filterAndGet(wildAnimals, housePetsAndInsects)}`);
function _filterAndGet(mainList, filterList) {
const filterSet = new Set(filterList);
const filteredMainList = mainList.filter(e => !filterSet.has(e));
const index = Math.floor(Math.random() * filteredMainList.length);
return filteredMainList[index];
}
function _get(array, label) {
const res = [];
for (const elem of array) {
for (const objKey of Object.keys(elem)) {
if (objKey === label) {
for (const item of elem[objKey]) {
res.push(item.name);
}
return res;
}
}
}
return res;
}
Example output:
Wild animals: ["Giraffe","Lion","Cat","Ladybug"]
House Pets and Insects: Cat,Dog,Ladybug,Spider
Random wild animal not in housePets and insects: Lion
You can try with this simple way by using Array.find() along with Array.some() methods.
Working Demo :
let animals = [{
"housePets": [
{ "name": "Cat", "food" : "Fish", "description": "Long tail, sharp claws" },
{ "name": "Dog", "food" : "Biscuits", "description" : "Humans best friend" }]
}, {
"wildAnimals": [
{ "name": "Giraffe", "food" : "Leafes", "description" : "A very long neck" },
{ "name": "Lion", "food" : "Meat", "description" : "Featured in Lion King" }]
}, {
"insects": [
{ "name": "Ladybug", "food" : "Leafes", "description" : "Red and black" },
{ "name": "Spider", "food" : "Flies", "description" : "From the friendly neighbourhood" }]
}];
let animalsArr2 = ['housePets'];
const res = animals.find((obj) => animalsArr2.some((elem) => Object.keys(obj).includes(elem)));
console.log(res);

Apply CSS style within .js var

I'm currently building a game which relies on a random number to show a particular string from an array within a .js file. What I want to do is effectively apply a span element to certain text within the array - eg. make positive outcomes green & negative red, however I can't figure out how to do this outside of html. Eg:
var data = [
{"label": "Question 1", "value": 1, "question": "Awareness: High, Consistency: Low."},
{"label": "Question 2", "value": 1, "question": "Consistency: High, Awareness: Low."},
]
A separate set of code, after selecting a random number, returns data[i].label. How would I set a span within js so that the "High" strings return in green, and "Low" return in red?
Cheers.
You have not specified much, but I went and did what I could.
First, your span
<span id="result">here we go</span>
The CSS file, minimalist, I did not include Bootstrap for this.
span {color:green}
.red{color:red}
The JS, the is no event, or event handler.
var data = [
{"label": "Question 1", "value": 1, "question": "Awareness: High, Consistency: Low."},
{"label": "Question 2", "value": 1, "question": "Consistency: High, Awareness: Low."}
]
The array, I have removed the trailing comma after the second object.
let outputs = data[0].question; This will hold the result from the array, data[0] targets the first object, you can also get map over the properties, but you have not entirely specified the scope and desired functionality.
var output = document.getElementById('result'); // the span element
output.innerText = outputs; // i prefer innerText to innerHTML
if (outputs.includes("Consistency: Low")) { // new string method includes, you can pass the whole ("Consistency: Low")in with no worries.
output.classList.toggle("red"); // if condidtion is true, toggle the red class
}
Codepen
https://codepen.io/damPop/pen/ZwvvGV?editors=0010
Uses classes
var data = [
{label: "Question 1", value: 1, awareness: 'High', consistency: 'Low' },
{label: "Question 2", value: 1, awareness: 'Low', consistency: 'High' },
{label: "Question 3", value: 1, awareness: 'Low', consistency: 'Low' },
{label: "Question 4", value: 1, awareness: 'High', consistency: 'High' }
];
const questionElement = document.getElementById('question');
const awarenessElement = document.getElementById('awareness');
const consistencyElement = document.getElementById('consistency');
document.getElementById('select').addEventListener('click', select);
select();
function select() {
const question = data[Math.floor(Math.random() * 4)];
questionElement.innerText = question.label;
awarenessElement.innerText = `Awareness: ${question.awareness}`;
awarenessElement.className = question.awareness;
consistencyElement.innerText = `Consistency: ${question.consistency}`;
consistencyElement.className = question.consistency;
}
.High {
background-color: green;
}
.Low {
background-color: red;
}
<span id="question"></span>
<div id="awareness"></div>
<div id="consistency"></div>
<button id="select">Select</button>

How to convert json array to java script using php?

I have this data...
{"quiz":
[{"question":"What is your favorite color?",
"choices":[{"prefix":"A","content":"Red"},{"prefix":"B","content":"Blue"},{"prefix":"C","content":"Yellow"},{"prefix":"D","content":"Pink"}]},
{"question":"What is the equivalent measurement of 1 feet?",
"choices":[{"prefix":"A","content":"12cm"},{"prefix":"B","content":"12px"},{"prefix":"C","content":"12mm"},{"prefix":"D","content":"12inch"}]},
{"question":"What is the combination of Green?",
"choices":[{"prefix":"A","content":"Yellow and Red"},{"prefix":"B","content":"Blue and Orange"},{"prefix":"C","content":"Yellow and Blue"},{"prefix":"D","content":"Black and Skyblue"}]}],"success":1}
and i want to convert it in java script like this one...
const myQuestions = [
{
question: "Who is the strongest?",
answers: {
a: "Superman",
b: "The Terminator",
c: "Waluigi, obviously"
},
correctAnswer: "c"
},
{
question: "What is the best site ever created?",
answers: {
a: "SitePoint",
b: "Simple Steps Code",
c: "Trick question; they're both the best"
},
correctAnswer: "c"
},
{
question: "Where is Waldo really?",
answers: {
a: "Antarctica",
b: "Exploring the Pacific Ocean",
c: "Sitting in a tree",
d: "Minding his own business, so stop asking"
},
correctAnswer: "d"
}
];
how can I achieve this one, because im making a quiz app which will view in mobile device by the use of webviewer. any help is much appreciated..
Here's a start of how you could potentially convert the array. Be aware, there is no correctAnswer column in your input, so it's impossible to convert:
var input = {"quiz":
[{"question":"What is your favorite color?",
"choices":[{"prefix":"A","content":"Red"},{"prefix":"B","content":"Blue"},{"prefix":"C","content":"Yellow"},{"prefix":"D","content":"Pink"}]},
{"question":"What is the equivalent measurement of 1 feet?",
"choices":[{"prefix":"A","content":"12cm"},{"prefix":"B","content":"12px"},{"prefix":"C","content":"12mm"},{"prefix":"D","content":"12inch"}]},
{"question":"What is the combination of Green?",
"choices":[{"prefix":"A","content":"Yellow and Red"},{"prefix":"B","content":"Blue and Orange"},{"prefix":"C","content":"Yellow and Blue"},{"prefix":"D","content":"Black and Skyblue"}]}],"success":1}
console.log(input.quiz.map(({question, choices}) => ({
question,
answers: choices.reduce((obj, v) => Object.assign(obj, {[v.prefix]: v.content}), {}),
correctAnswer: "?",
})));

Load multiple JSON objects from multiple files

I am trying to create a quiz website. The quiz data (questions, answers, and correct answer) are stored in JSON files. Everything works as is, but I would like to include a unique image in each individual JSON file. I figured that the best way would be to create another object; meaning I'd have the structure shown below:
[
{"adImage" : "images/NoOvertake.jpg"}
],
[
{
"question" : "Before making a U - turn in the road you should always:",
"answers":[
{"id" : 0, "text" : "Select a higher gear than normal"},
{"id" : 1, "text" : "Signal so that other drivers can slow down"},
{"id" : 2, "text" : "Look over your shoulder for final confirmation"},
{"id" : 3, "text" : "Give another signal as well as using your indicators"}
],
"correct" : [2],
"allAns":[]
},
{
"question" : "As a driver what do you understand by the term 'Blind Spot'?",
"answers" : [
{"id" : 0, "text" : "An area covered by your left hand mirror" },
{"id" : 1, "text" : "An area not covered by your headlights" },
{"id" : 2, "text" : "An area covered by your right hand mirror" },
{"id" : 3, "text" : "An area not covered by your mirrors" }
],
"correct" : [3],
"allAns":[]
}
]
This is the JavaScript which used to work before I added the new image object above all the questions:
var app = angular.module('myQuiz',[]);
app.controller('QuizController'
['$scope','$http','$q','$sce',function($scope,$http,$q,$sce){
var jsonData = ['alertness','attitude', 'safety and your vehicle',
'safety margins','hazard awareness',
'vulnerable road users','other type of vehicles',
'vehicle handling','dual carriageway rules',
'rules of the road','road and traffic signs',
'documents','accidents','vehicle loading'];
var promise = [];
$scope.allQuestions = [];
for(var i=0;i<jsonData.length;i++) {
promise.push($http.get(jsonData[i]+'.json'))
}
$q.all(promise).then(function(quizData){
for(var i=0;i<quizData.length;i++) {
$scope.allQuestions[i] = {};
$scope.allQuestions[i].quizName = jsonData[i];
$scope.allQuestions[i].data = quizData[i].data;
$scope.allQuestions[i].score = 0;
$scope.allQuestions[i].activeQuestion = -1;
$scope.allQuestions[i].activeQuestionAnswered = 0;
$scope.allQuestions[i].percentage = 0;
var questionNumber = quizData.length;
}
});
]);
Now, not even the questions will show up. I appreciate any sort of help, or even alternative solutions. All I need to do is add an image which would remain there for every question. What HTML code would I need to show the image?
Thanks in advance!
A valid JSON object only has one root element. You can use JSON linters to see if your JSON is valid http://jsonlint.com. I'd suggest to use something like this as a structure.
{
"adImage": "images/NoOvertake.jpg",
"questions": [
{
"question": "Before making a U - turn in the road you should always:",
"answers": [
{
"id": 0,
"text": "Select a higher gear than normal"
},
{
"id": 1,
"text": "Signal so that other drivers can slow down"
},
{
"id": 2,
"text": "Look over your shoulder for final confirmation"
},
{
"id": 3,
"text": "Give another signal as well as using your indicators"
}
],
"correct": [
2
],
"allAns": []
},
{
"question": "As a driver what do you understand by the term 'Blind Spot'?",
"answers": [
{
"id": 0,
"text": "An area covered by your left hand mirror"
},
{
"id": 1,
"text": "An area not covered by your headlights"
},
{
"id": 2,
"text": "An area covered by your right hand mirror"
},
{
"id": 3,
"text": "An area not covered by your mirrors"
}
],
"correct": [
3
],
"allAns": []
}
]
}

Adding key/values pairs to JSON map down one level

I'm trying to dynamically add new key/value pairs to an existing json map using jquery/javascript. An example of my structure is as follows:
var widgetTypes = {
"CLASS_A": {
"A1": "A1 Description",
"A2": "A2 Description"
},
"CLASS_B": {
"B1": "B1 Description",
"B2": "B2 Description"
}
};
How do I append a key/value pair to either class (i.e. CLASS_A or CLASS_B). For example, how would I add item A3 with description "A3 Description" to the CLASS_A section of the structure so that I then had the following?
var widgetTypes = {
"CLASS_A": {
"A1": "A1 Description",
"A2": "A2 Description"
"A3": "A3 Description"
},
"CLASS_B": {
"B1": "B1 Description",
"B2": "B2 Description"
}
};
I know you can do something like widgetTypes['CLASS_A'].type = 'A3' etc. but I can't seem to get it quite right (or I'm way off the track). I found a lot of examples of adding items the level above (i.e. adding a CLASS_C) but nothing for what I'm interested in doing.
There are several ways:
. Dot notation.
[] Bracket notation.
Object.defineProperty() method.
var widgetTypes = {
"CLASS_A": {
"A1": "A1 Description",
"A2": "A2 Description"
},
"CLASS_B": {
"B1": "B1 Description",
"B2": "B2 Description"
}
};
1.
widgetTypes.CLASS_A.A3 = "A3 Description"
2.
widgetTypes["CLASS_A"]["A3"] = "A3 Description"
3.
Object.defineProperty(widgetTypes.CLASS_A, 'A3', {
value: "A3 Description",
writable: true,
enumerable: true,
configurable: true
});
Option 3 has several other advantages over the two that you can configure the property behavior.
widgetTypes.CLASS_A.A3 = "A3 Description";
or equivalently
widgetTypes["CLASS_A"]["A3"] = "A3 Description";

Categories

Resources