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

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)

Related

Merge two array of objects in Angular 8 if the item of second array contains the id of the first object of array

I am trying to merge two array of objects which the first array has a json file and the second the same but the second it holds the id of the first array of objects.
I am trying to add the second array of objects for each to the right item of the first array of objects.
As you can see the comments has an postId where it knows which post it belongs.
My json file it looks like this.
{
"posts": [
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure voluptatem occaecati omnis eligendi aut ad voluptatem doloribus vel accusantium quis pariatur molestiae porro eius odio et labore et velit aut"
},
{
"userId": 1,
"id": 4,
"title": "eum et est occaecati",
"body": "ullam et saepe reiciendis voluptatem adipisci sit amet autem assumenda provident rerum culpa quis hic commodi nesciunt rem tenetur doloremque ipsam iure quis sunt voluptatem rerum illo velit"
},
{
"userId": 1,
"id": 5,
"title": "nesciunt quas odio",
"body": "repudiandae veniam quaerat sunt sed alias aut fugiat sit autem sed est voluptatem omnis possimus esse voluptatibus quis est aut tenetur dolor neque"
},
and the same json but with another API to get data.
"comments": [
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo#gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos tempora quo necessitatibus dolor quam autem quasi reiciendis et nam sapiente accusantium"
},
{
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "Jayne_Kuhic#sydney.com",
"body": "est natus enim nihil est dolore omnis voluptatem numquam et omnis occaecati quod ullam at voluptatem error expedita pariatur nihil sint nostrum voluptatem reiciendis et"
},
{
"postId": 1,
"id": 3,
"name": "odio adipisci rerum aut animi",
"email": "Just#do.it",
"body": "consectetur cumque impedit blanditiis non eveniet odio maxime blanditiis amet eius quis tempora quia autem rem a provident perspiciatis quia"
},
{
"postId": 1,
"id": 4,
"name": "alias odio sit",
"email": "Just#do.it",
"body": "impedit nostrum id quia aut est fuga est inventore vel eligendi explicabo quis consectetur aut occaecati repellat id natus quo est ut blanditiis quia ut vel ut maiores ea"
},
{
"postId": 1,
"id": 5,
"name": "vero eaque aliquid doloribus et culpa",
"email": "Hayden#althea.biz",
"body": "harum non quasi et ratione tempore iure ex voluptates in ratione harum architecto fugit inventore cupiditate voluptates magni quo et"
},
{
"postId": 2,
"id": 6,
"name": "et fugit eligendi deleniti quidem qui sint nihil autem",
"email": "Presley.Mueller#myrl.com",
"body": "doloribus at sed quis culpa deserunt consectetur qui praesentium accusamus fugiat dicta voluptatem rerum ut voluptate autem voluptatem repellendus aspernatur dolorem in"
},
{
"postId": 2,
"id": 7,
"name": "repellat consequatur praesentium vel minus molestias voluptatum",
"email": "Just#do.it",
"body": "maiores sed dolores similique labore et inventore et quasi temporibus esse sunt id et eos voluptatem aliquam aliquid ratione corporis molestiae mollitia quia et magnam dolor"
},
I have created a model and service to define data and to get data.
export class Post {
userId: number;
id: number;
title: string;
body: string;
}
import {Injectable} from '#angular/core';
import {HttpClient} from '#angular/common/http';
import {Observable} from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class PostService {
private baseUrl = 'http://localhost:3000/posts';
constructor(private http: HttpClient) { }
getPost(id: number): Observable<any> {
return this.http.get(`${this.baseUrl}/${id}`);
}
getPostsList(): Observable<any> {
return this.http.get(`${this.baseUrl}`);
}
deletePost(id: number): Observable<any> {
return this.http.delete(`${this.baseUrl}/${id}`);
}
And this is the component
export class PostsListComponent implements OnInit {
public posts: Observable<Post[]>;
constructor(private postsService: PostService) { }
ngOnInit() {
this.comments$ = this.commentsService.getCommentsList();
this.posts = this.postsService.getPostsList();
this.groupedComments$ = this.comments$.pipe(
map(comments => lodash.groupBy(comments, 'postId'),
));
}
}
HTML code
<tr class="row" *ngFor="let post of posts | async">
<td class="col">{{post.title}}</td>
<td class="col-6">{{post.body}}</td>
<td class="col"><button (click)="deletePost(post.id)" class="btn btn-danger">Delete</button>
<button (click)="postDetails(post.id)" class="btn btn-info" style="margin-left: 10px">Details</button>
</td>
</tr>
I recommend to group the comments by postId, for example with lodash
this.groupedComments$ = this.comments$.pipe(
map(comments => lodash.groupBy(comments, 'postId')),
);
Then you can simply access this object in template
<tr class="row" *ngFor="let post of posts | async">
<td class="col">{{post.title}}</td>
<td class="col-6">{{post.body}}</td>
<td class="col">
<div *ngFor="let comment of groupedComments[post.id]">{{comment}}</div>
</td>
<td class="col"><button (click)="deletePost(post.id)" class="btn btn-danger">Delete</button>
<button (click)="postDetails(post.id)" class="btn btn-info" style="margin-left: 10px">Details</button>
</td>
</tr>
(async-pipe groupedComments$ anywhere before)
Edited:
interface Comment {
postId: number;
id: number;
name: string;
email: string;
body: string;
}
interface CommentGroup {
[key: number]: Comment[];
}
comments$: Observable<Comments[]>;
groupedComments$: Observable<CommentGroup>;

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/

Datatables Server side renders too many pages for pagination

I am using the Datatables.net plugin and made my own server side script to return the json data, the json code looks like this.
{
"draw": 1,
"recordsTotal": 100,
"filteredTotal": 100,
"data": [
[
"10",
"2",
"Dignissimos voluptatem odit commodi tenetur eaque ut. Reprehenderit asperiores accusamus ut enim rem fugiat suscipit. Beatae illo ipsum et non commodi. Sed consequuntur assumenda optio dignissimos.",
"Occaecati ut pariatur optio maiores delectus ipsum rerum ipsam. Porro est dolores consequatur amet fugit cumque.",
"9",
"4",
"3",
"Repellat qui aliquam qui nostrum illum soluta debitis sint. Qui ut autem ut qui sint dolorum. Laborum neque ipsam eum non ut. Vel et expedita qui aut tempora qui."
],
[
"11",
"4",
"Pariatur rerum dolorem in quibusdam. Sunt iusto impedit perspiciatis et rerum possimus. Magni mollitia eos architecto. Laborum voluptatem mollitia dolorem porro.",
"Doloribus vel aut quia ea et non consequuntur eligendi. Aut vero accusamus ipsa tenetur ullam perspiciatis. Exercitationem est facilis animi. Et alias modi dignissimos repudiandae.",
"0",
"2",
"9",
"Dolorem ullam ut illo est officia. Nesciunt nisi porro aut. Unde non pariatur ab aut. Enim quis ratione et ipsum voluptatem placeat."
],
[
"12",
"2",
"Consequatur dignissimos consequuntur repellendus enim quod. Aut ipsa cum enim perferendis. Qui et odit voluptatem ex quia temporibus quod. Culpa suscipit qui molestiae est labore.",
"Quis sit quis et et harum ipsum accusantium. Quisquam aut fugiat ipsum ut velit autem cupiditate. Consequatur aut et voluptates totam porro et.",
"0",
"4",
"6",
"Dicta aut hic quia deleniti soluta soluta. Neque accusantium beatae ut et autem quo. Consequatur placeat vel dolores magnam alias dolorem. In nam et aspernatur esse ea reiciendis."
],
[
"13",
"9",
"Qui sit aut repellat consequatur quia reprehenderit non. Repellat quia quaerat aspernatur consequatur dolorum temporibus maxime illo. Recusandae optio explicabo saepe cupiditate.",
"Nihil quae est suscipit ullam sed tempora nesciunt voluptates. Dolorum numquam temporibus est praesentium atque non cum. Quo veniam voluptatem repudiandae voluptas corrupti ipsa.",
"1",
"6",
"1",
"Harum officia iusto eveniet qui et. Dolores veritatis et error nam possimus nemo. Non natus sunt laborum magnam. Eum rerum laboriosam in eligendi nihil dolores recusandae distinctio."
],
[
"14",
"2",
"Sed veritatis et illum odio. Eius recusandae cumque qui animi quia enim. Unde repellendus ut sequi. Ea fugiat quasi ut in aut.",
"Rerum nam deleniti voluptates quod fugit. Est exercitationem repellendus voluptates id. Minima dicta modi maxime.",
"8",
"0",
"1",
"Magnam et fugit tempore qui praesentium. Quia sit eum quo et quo aut. Iusto non sequi ducimus sint qui."
]
]
}
My request looks like this.
draw=1&columns[0][data]=0&columns[0][name]=p.id&columns[0][searchable]=false&columns[0][orderable]=false&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=1&columns[1][name]=p.supplier_id&columns[1][searchable]=false&columns[1][orderable]=false&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=2&columns[2][name]=p.title&columns[2][searchable]=false&columns[2][orderable]=false&columns[2][search][value]=&columns[2][search][regex]=false&columns[3][data]=3&columns[3][name]=p.permalink&columns[3][searchable]=false&columns[3][orderable]=false&columns[3][search][value]=&columns[3][search][regex]=false&columns[4][data]=4&columns[4][name]=p.mpn&columns[4][searchable]=false&columns[4][orderable]=false&columns[4][search][value]=&columns[4][search][regex]=false&columns[5][data]=5&columns[5][name]=p.barcode&columns[5][searchable]=false&columns[5][orderable]=false&columns[5][search][value]=&columns[5][search][regex]=false&columns[6][data]=6&columns[6][name]=p.spc&columns[6][searchable]=false&columns[6][orderable]=false&columns[6][search][value]=&columns[6][search][regex]=false&columns[7][data]=7&columns[7][name]=p.description&columns[7][searchable]=false&columns[7][orderable]=false&columns[7][search][value]=&columns[7][search][regex]=false&start=0&length=5&search[value]=&search[regex]=false&_=1475131244317
Then I use pagination on my datatables but I should expect 20 pages with 5 records making it a total of 100 when I try it the pagination is working but it generates too many pages it goes on endlessly.
This is the javascript where I initialize the datatable.
<script>
$('#products').DataTable({
"processing": true,
"serverSide": true,
"ajax": "/product/data",
"searching": false,
"ordering": false,
"columns": [
{ name: 'p.id', "searchable": true },
{ name: 'p.supplier_id', "searchable": false },
{ name: 'p.title', "searchable": false },
{ name: 'p.permalink', "searchable": false },
{ name: 'p.mpn', "searchable": false },
{ name: 'p.barcode', "searchable": false },
{ name: 'p.spc', "searchable": false },
{ name: 'p.description', "searchable": false }
]
});
</script>
I found the solution the key filteredTotal in the return JSON has to be recordsFiltered. After I changed this my pagination worked normally.

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

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.

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.

Categories