how to put image into a page from a json object? - javascript

I'm writing a news site and with all the news stored in json files. Here's an example of the json Schema:
{
title: "lorem ipsum",
body: "Qui Quo Omnis Nulla Porro Quidem Quisquam Consequuntur Neque Expedita Iu [image1 goes here]. Nditiis Mollitia Facere Adipisci Fugiat Minus Vero Nostrum Sint Se. I Et Culpa Vitae Quos Ullam Optio Est Debitis Reprehenderit Alia. Dolorem Necessitatibus Accusantium Voluptatibus Maiores Dolores Quae Velit Te. Tur Non Officia Assumenda Obcaecati Veritatis Minima Dicta Im [image 2 goes here]",
author: "author",
images: ["path/to/image1","path/to/image2]
}
How can i make images appear in the right position?
(i'm using nunjucks templating engine if it's usefull for the answer)

I think you should change your json schema if possible.
{
"title": "Lorem Ipsum",
"bodies": [
{
"text": "Qui Quo Omnis Nulla Porro Quidem Quisquam Consequuntur Neque Expedita Iu",
"image": "path/to/image1"
},
{
"text": "Blah blah blah",
"image": "path/to/image2"
}
],
"author": "author"
}
Then you will know that the image should always go after the text. You can even add an empty text to begin with an image.
Edit: Just for fun, I put together a short script that creates an array with the news' text and the image that goes after. I still think you should instead update your schema.
var myNew = {...}
var magic = myNew.body.split(/\[.*?\]/).filter(n=>n);
var whatsthis = magic.reduce((fullArray,text, index)=>{
fullArray.push(text);
fullArray.push(test.images[index]);
return fullArray;
}, []);
console.log(whatsthis);
This outputs ["Qui Quo Omnis Nulla Porro Quidem Quisquam Consequuntur Neque Expedita Iu ", "path/to/image1", ". Nditiis Mollitia Facere Adipisci Fugiat Minus Ve…ia Assumenda Obcaecati Veritatis Minima Dicta Im ", "path/to/image2"].
https://jsfiddle.net/Lfpab33y/
If it makes things easier, you can change
fullArray.push(text);
fullArray.push(test.images[index]);
into
fullArray.push({type:"text", content:text});
fullArray.push({type:"imagePath", content:test.images[index]});
so you know whether it's text or imagePath and do something about it in your template.

Related

How to display all JSON key and value without using key [duplicate]

This question already has answers here:
How to get all properties values of a JavaScript Object (without knowing the keys)?
(25 answers)
Closed 1 year ago.
It maybe basic, but i'm stuck of how to display JSON file in react native
For example, i'm get a json object by
const [post, setPost] = React.useState(null);
const baseURL = 'https://jsonplaceholder.typicode.com/posts/1';
React.useEffect(() => {
axios.get(baseURL).then(response => {
console.log(response.data);
setPost(response.data);
});
}, []);
And it return like
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Now i want to display on screen something like
1
1,
sunt aut facere repellat provident occaecati excepturi optio reprehenderit,
quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto
I know, i can use post.userId or post.id to display each of them, but if i have 1000 items like this, how can i display them without call keys?
i tried
{Object.keys(post).map(i => (
<Text>{i}</Text>
))}
But it return something like
{
"userId"
"id"
"title"
"body"
}
So how can I display data instead of key without using key?
You can use Object.values to get the enumerable property values and Array.join to join the resulting array into a string:
const obj = {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
const res = Object.values(obj).join('\n')
console.log(res)
Your Object.keys approach is also fine - you'll just need to get the value of the property:
const obj = {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
const res = Object.keys(obj).map(i => obj[i]).join('\n')
console.log(res)

Get a JSON object key as a link

I am trying to get a json as a json format, but the keys as a link.
So that, Whenever i click on the link, I should get the output as key with an index
example
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio
reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et
cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt
rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor
beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil
molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi
nulla"
}
]
When i click on userId where id is 1, I should get the otput as 0.userId
Can anyone suggest me a way to get a proper solution for my problem.
okay if you are not using jquery try this out
url = Object.keys(jsonObject).map(function(someparameter) {
return encodeURIComponent(someparameter) + '=' + encodeURIComponent(jsonBoject[someparameter])
}).join('&')
I think you are looking something like this https://json-ld.org/

JavaScript: get scrollY position of searched text on body [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need scrollY position of searched text. How to find text in body and get scrollY position of the found text.
Following code is an example about question:
(all is clear)
<script>
function getScrollYPosition(var str){
/* step 1: search str in <body> and found.
* step 2: get scrollY position of found str.
* step 3: return position. (500)
*/
}
</script>
<body>
<p>Hello world</p> /*For example scrollY position is 500*/
<p>...</p>
<p>...</p>
</body>
You could first match the text string,
wrap it into an (span) element
and than calculate that element offset position
Here's a quick example
var word = 'dolor';
var rgx = new RegExp('\\b('+word+')\\b', 'ig');
// CREATE SPAN ELEMENTS WHAT WILL WRAP THE QUERY STRING (WORD)
$('div, div *').contents().filter(function() {
return this.nodeType === 3;
}).each(function() {
$(this).replaceWith($(this).text().replace(rgx, "<span class='match'>$1</span>"));
});
// COLLECT ALL SPAN POSITIONS
var positions = $('.match').map(function(){
return this.getBoundingClientRect().top;
}).get();
alert(positions);
div{font-size:50px;}
span.match{background: gold;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut voluptatum, provident saepe. Culpa animi sint, itaque iure error hic qui blanditiis perspiciatis adipisci, libero quia veritatis dignissimos quasi id cumque!</div>
<div>Magni cupiditate laudantium, corrupti commodi, reiciendis consequuntur recusandae minima tempore id placeat rerum saepe molestiae, nulla illo, dolores distinctio aliquid asperiores esse maxime voluptatibus corporis at. Commodi eius magni esse!</div>
<div>Maiores explicabo, dolor nemo mollitia cumque et nobis quae consectetur alias dicta quod facere saepe aspernatur sint ex soluta nulla veritatis ab. Sunt aspernatur distinctio quam alias quis possimus reiciendis impedit.</div>
<div>Est sequi eius nam, odio ut commodi quam omnis aperiam, vel, sunt quaerat adipisci voluptates natus possimus consequuntur corporis atque facere corrupti, rem autem modi ipsam inventore nobis! Itaque, modi?</div>
<div>Velit, cumque in dicta ratione iste autem, atque dolor magni optio, excepturi qui ipsam laboriosam modi quidem cupiditate sapiente perferendis! Iste eos fuga ut eum deserunt repellendus ex qui, illo eaque!</div>
<div>Ullam a, labore aperiam ex culpa nesciunt ipsam voluptatibus maiores consequatur qui repellendus obcaecati tenetur, consectetur eos, ut voluptate, nemo placeat soluta odit? Error, Dolor, voluptatibus! Id sed alias et consectetur.</div>
<div>Ipsa pariatur tenetur, nobis recusandae deserunt quisquam nesciunt, ex consequuntur minus voluptatem dolores officiis itaque fuga reiciendis dolor praesentium quae maxime repudiandae. Quibusdam sint fugit soluta pariatur, alias, eveniet natus culpa!</div>
You could be a little more specific with your answer. If I understand correctly you need to find an element that contains a given text and get its vertical offset. You could try the following:
$($(":contains(YOUR_TEXT)").slice(-1)[0]).offset().top

Trying to create multi-filter in AngularJS to filter JSON data by month and year id's

I have implemented AngularJS inside of the RoR framework. I am trying to create a multi-filter for the "ng-repeat" method to filter the JSON data by "month_id" and "year_id".
Currently I have the following code:
JSON:
[
{ "date":"October 4, 2015",
"month_id":"10",
"year_id":"2015",
"name":"Chris",
"title":"Painter",
"company":"Freelancer",
"description":"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" },
{ "date":"October 3, 2015",
"month_id":"10",
"year_id":"2015",
"name":"Rebecca",
"title":"Writer",
"company":"John H. Hickenloop",
"description":"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" },
{ "date":"October 22, 2014",
"month_id":"10",
"year_id":"2014",
"name":"Josh",
"title":"Riddler",
"company":"Florida Museum",
"description":"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." }
]
Controller:
var myApp = angular.module('myApp', []);
myApp.controller("MyController", function MyController($scope, $http){
$http.get("/assets/data.json").success(function(data){
$scope.artists = data;
String.prototype.trunc = String.prototype.trunc ||
function(n){
// this will return a substring and
// if its larger than 'n' then truncate and append '...' to the string and return it.
// if its less than 'n' then return the 'string'
return this.length>n ? this.substr(0,n-1)+'...' : this;
};
$scope.myFilter = function(){
var currentDate = new Date;
return year_id === currentDate.getFullYear() && month_id === (currentDate.getMonth() + 1);
};
});
});
HTML:
<div ng-controller="MyController">
<ul>
<li ng-repeat="item in artists | filter: myFilter">
<h1>{{item.date}}</h1>
<p>{{ item.description.trunc(100) }}</p>
</li>
</ul>
</div>
Your main issue is that you're comparing numbers to strings and using the strong comparison operator (remember, '2' !== 2). Try using the .toString() method in your filter function on currentDate.getFullYear() and currentDate.getMonth(). Or you could use the weak comparison operator, ==.
'2' == 2; // true
'2' === 2; // false
The Angular way of doing this would be to write your own filter and keep that logic outside of your controller and, in so doing, make that function reusable everywhere in your app. You can find documentation for writing custom filters at https://docs.angularjs.org/guide/filter. I would approach this like so:
myApp
.controller('MyController', function MyController($scope, $http) {
/** YOUR CODE HERE */
})
.filter('thisMonth', [function() {
return function(array) {
var results = [],
today = new Date(),
month = (today.getMonth() + 1).toString(),
year = today.getFullYear().toString();
angular.forEach(array, function(item, index) {
if (item.month_id === month && item.year_id === year) {
this.push(item);
}
}, results);
return results;
};
}]);
Then in your ng-repeat, you could just use:
<ul>
<li ng-repeat="item in items|thisMonth">item.date</li>
</ul>
Or, in your controller, you could use
$scope.sortedItems = $filter('thisMonth')($scope.items);
EDIT: Using that last approach, you would need to include $filter as a dependency.

Randomly selecting a paragraph from Array list Javascript

I am working on my own Lorem Ipsum generator, with the added bonus of generating the corresponding HTML formatting code in a box beside it.
So, the paragraph is generated via this button
<button id="generate" type="button" onclick="LoremIpsumRandom()">1 Paragraph</button>
and is generated here
<p id="textarea"></p>
function LoremIpsumRandom()
{
//global to store previous random int
_oldInt = null;
var pickRandom = function(paragraphArray)
{
//random index of paragraphArray
var randomInt = Math.floor(Math.random()*paragraphArray.length);
//ensure random integer isn't the same as last
if(randomInt == _oldInt)
pickRandom(paragraphArray);
else{
_oldInt = randomInt;
return paragraphArray[randomInt];
}
}
//your lorem ipsum paragraphs
var paragraphArray = [
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.",
"Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.",
"Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.",
"Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?", "Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.",
"Et harum quidem rerum facilis est et expedita distinctio.", "Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.",
"Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.",
"Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
];
//update element content (e.g. `<div>` with paragraph
document.getElementById("textarea").innerHTML = pickRandom(paragraphArray);
//document.getElementById("textarea-code").innerText = pickRandom("<P>" + (paragraphArray) + "</P>");
}
No point including the CSS to be honest - it's just standard text boxes and auto-generated buttons.
So, the issue is that although I can generate the normal paragraph in the id="textarea" section, I want to be able to generate a raw HTML version as well (with the paragraph and line breaks code being shown.) So far, I've been able to generate the raw HTML with no issues, but when I added #pixelbobby 's section (which makes sure that when a sentence is selected, the next selection won't be the same, as true randomness can sometimes generate), the code doesn't work. In some instances, it's generated the raw HTML, but the generated paragraph is a different one.
The other functions (generating lists, multi-paragraphed sections and multi-levelled lists) utilise the raw HTML and output correctly, and it all runs smoothly. The raw HTML is always outputted to
<p id="textarea-code"></p>
which is next to the first textarea section.
Can someone tell me how I can modify the script so that the raw HTML part of the script generates the same paragraph as the result of the pickRandom(paragraphArray)
So,
This - document.getElementById("textarea-code").innerText = pickRandom("<P>" + (paragraphArray) + "</P>");
needs to be the same as - document.getElementById("textarea").innerHTML = pickRandom(paragraphArray);
but with the raw HTML specified in the pickRandom() part of the line.
Can anyone help?
Thanks :)
You can save the result of pickRandom(paragraphArray) in a variable and use it twice:
var randomParagraph = pickRandom(paragraphArray); //save the result of pickRandom
document.getElementById("textarea").innerHTML = randomParagraph;
document.getElementById("textarea-code").innerText = "<P>" + randomParagraph + "</P>");

Categories