Logic for reconstruction of json data - javascript

Hope you are doing well.
[ {
"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": 2,
"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"
},
{
"userId": 3,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
]
Considering there are multiple objects for each userId and I want to group them together in the below format.
const json2 = {
1: [{},{},{}],
2:[{},{},{}],
3:[{},{},{}],
}
Any help will be appreciated.
Thanks in Advance

You can do it using the reduce function, but next time please provide what you tried before asking.
const input = [{
"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": 2,
"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"
},
{
"userId": 3,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
];
const output = input.reduce((acc, el) => {
acc[el.userId]??=[];
acc[el.userId].push(el);
return acc;
}, {})
console.log(output);

Related

How access specific property for each object in list

I made a list (j_list) contain some post. I want a way to access on each body property present on the list.
My goal is find if a specific word exist on body property string.
const j_list =[
const post = {
"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\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
},
const post = {
"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\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
},
const post = {
"postId": 1,
"id": 3,
"name": "odio adipisci rerum aut animi",
"email": "Nikita#garfield.biz",
"body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
}
]
I try this on my code :
for (post in j_list){
if(post.body.includes("quasi") > -1){
console.log("This post contain that word")
} else {
console.log("This post doesn't contain any search word")
}
You are defining the array in a wrong way. Each element should be separated via a , without const post.
const j_list = [
{
"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\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis 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\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
},
{
"postId": 1,
"id": 3,
"name": "odio adipisci rerum aut animi",
"email": "Nikita#garfield.biz",
"body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
}
];
for (const post of j_list){
if(post.body.includes("quasi") > -1){
console.log("This post contain that word")
} else {
console.log("This post doesn't contain any search word")
}
}
Change your declaration to an array of objects, then access those objects in a loop; Example:
const j_list = [{
"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\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis 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\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
}, {
"postId": 1,
"id": 3,
"name": "odio adipisci rerum aut animi",
"email": "Nikita#garfield.biz",
"body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
}
];
// string includes returns a boolean
j_list.forEach(function(postel, index) {
// console.log(postel, postel.body);
if (postel.body.includes("quasi")) {
console.log("This post contain that word")
} else {
console.log("This post doesn't contain any search word")
}
});

Fetch multiple posts from JSON Placeholder with one API call

So, my question is, can you fetch multiple posts from JSON Placeholder API, but call fetch once, and fetch 12 posts for example. This is what I did so far, but when I go into network in inspect element, I get 12 API calls, and I want it to be 1 if it is possible
const fetchPosts = (id) => {
fetch("https://jsonplaceholder.typicode.com/posts/" + id)
.then(function (response) {
return response.json();
})
.then((json) => {
var result = document.querySelector(".wrapper");
result.innerHTML += "<div class=\"posts\">" + json.title + "</div>";
});
};
for(let i = 0; i <= 12; i++) {
fetchPosts(i);
}
<div class="wrapper"></div>
The API supports a filter. You can pass a list of IDs and other properties, e.g.:
fetch('https://jsonplaceholder.typicode.com/posts?id=0&id=1&id=2&id=3&id=4&id=5&id=6&id=7&id=8&id=9&id=10&id=11')
.then((response) => response.json())
.then((json) => console.log(json));
It sends one request and returns a response containing an array of posts:
[
{
"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"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
{
"userId": 1,
"id": 4,
"title": "eum et est occaecati",
"body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
},
{
"userId": 1,
"id": 5,
"title": "nesciunt quas odio",
"body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
},
{
"userId": 1,
"id": 6,
"title": "dolorem eum magni eos aperiam quia",
"body": "ut aspernatur corporis harum nihil quis provident sequi\nmollitia nobis aliquid molestiae\nperspiciatis et ea nemo ab reprehenderit accusantium quas\nvoluptate dolores velit et doloremque molestiae"
},
{
"userId": 1,
"id": 7,
"title": "magnam facilis autem",
"body": "dolore placeat quibusdam ea quo vitae\nmagni quis enim qui quis quo nemo aut saepe\nquidem repellat excepturi ut quia\nsunt ut sequi eos ea sed quas"
},
{
"userId": 1,
"id": 8,
"title": "dolorem dolore est ipsam",
"body": "dignissimos aperiam dolorem qui eum\nfacilis quibusdam animi sint suscipit qui sint possimus cum\nquaerat magni maiores excepturi\nipsam ut commodi dolor voluptatum modi aut vitae"
},
{
"userId": 1,
"id": 9,
"title": "nesciunt iure omnis dolorem tempora et accusantium",
"body": "consectetur animi nesciunt iure dolore\nenim quia ad\nveniam autem ut quam aut nobis\net est aut quod aut provident voluptas autem voluptas"
},
{
"userId": 1,
"id": 10,
"title": "optio molestias id quia eum",
"body": "quo et expedita modi cum officia vel magni\ndoloribus qui repudiandae\nvero nisi sit\nquos veniam quod sed accusamus veritatis error"
},
{
"userId": 2,
"id": 11,
"title": "et ea vero quia laudantium autem",
"body": "delectus reiciendis molestiae occaecati non minima eveniet qui voluptatibus\naccusamus in eum beatae sit\nvel qui neque voluptates ut commodi qui incidunt\nut animi commodi"
}
]
Example:
fetch("https://jsonplaceholder.typicode.com/posts?id=0&id=1&id=2&id=3&id=4&id=5&id=6&id=7&id=8&id=9&id=10&id=11")
.then(res => res.json())
.then(data => {
const html = data.reduce((acc, el) => acc + "<div class=\"posts\">" + el.title + "</div>", '');
const result = document.querySelector(".wrapper");
result.innerHTML = html;
});
<div class="wrapper"></div>
JSONPlaceholder is based on JSON Server and supports pagination. You can achieve the same result with
fetch('https://jsonplaceholder.typicode.com/posts?_page=0&_limit=12')
.then((response) => response.json())
.then((json) => console.log(json));

Fix a dropdown filter

I've been trying since this weekend implement this but no success so far.
I have a dropdown that should display items available on every event.
"id": "80773bce-7baf-49ae-8e65-328064a97116",
"title": "Sed sit qui enim corrupti magni at et voluptatum atque.",
"address": "69706 Lester Drive, Bedfordshire, Wilmington",
"guests": 70,
"budget": "65947.00",
"created_at": "2022-03-21T21:37:27.700+00:00",
"updated_at": "2022-03-21T21:37:27.700+00:00",
"is_public": false,
"description": "Fuga illo amet. Nihil omnis quae inventore repudiandae iure excepturi. Sunt necessitatibus harum culpa aliquid asperiores tenetur. Rem doloribus minus beatae officiis. Reprehenderit iure consequatur ea voluptates itaque voluptate vel dolorem reiciendis. Illo omnis et.\n \rDicta magnam et architecto ex cumque. Fugiat velit ullam deserunt perferendis consequuntur libero excepturi illum aspernatur. Quo iure libero vitae voluptatem aliquid qui dolores perspiciatis. Sed libero iusto ea odit incidunt iste libero.",
"event_date": "2022-03-21",
"start_hour": "2022-03-21T10:26:06.000Z",
"end_hour": "2022-03-21T10:26:06.000Z",
"landmark": "-11.9522,179.1757",
"location": "Laudantium veritatis animi ut quo est dolor inventore voluptate iure.",
"customer": null,
"eventType": null,
"items": [
{
"id": "70d32cee-a0fc-458a-b3e0-1bd0dbd4fdb5",
"title": "Sunt et unde eaque.",
"description": "Aut fugit voluptas explicabo animi. Illum reiciendis saepe minima dolore saepe pariatur omnis et et. Qui ratione rerum voluptatem voluptatem natus voluptatem eligendi. Iure sint et quae cumque sit neque. Similique magnam reprehenderit.",
"order": 97,
"enabled": true,
"created_at": "2022-03-21T21:37:27.702+00:00",
"updated_at": "2022-03-21T21:37:27.702+00:00"
}
],
"county": null
},
This should be the return from API.
Data is an array of objects and I must display all it's items under "eventType" line.
When I display it I must select one option and then should return only events that has that item on it's service.
So far, what I did was:
const mappedEventsData = eventsData.map((item) => {
return item.items[0];
});
And I succesfully rendered those . Then I passed it's title or id as paramater and my state is ok with that.
When I try to filter it however I cannot do it. I tried to console.log
useEffect(() => {
getData();
getEventsData();
console.log(mappedEventsData.includes(searchByTitle));
}, [searchByTitle]);
{mappedEventsData
.filter((item) => {
if (!item) return false;
return item.title.toLowerCase();
})
// .filter((item, index) => index < 3)
?.map((item) => {
return (
<option onClick={() => handleChangeSearchByEvents(item.id)} key={item.id}>
{item.title}
</option>
);
})}
and it always returns false.
How can I fix it and make it work?

How to display data(images) from a local Json file

I am new to React and am trying to figure out how to parse this data file to create a number of divs with the images as backgrounds and the text overlayed. Right now, I am having a hard time with even getting any data to display on the page without editing the json file to have export const = images instead of what it is currently. The images listed in my example code are different than actual. Any help is greatly appreciated! Thanks!
images.json
{
"images": [
{
"id": "1425ac9e-5718-4e2e-af43-132dcf58246b",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"thumb": "https://source.unsplash.com/user/erondu/1600x900.jpg",
"title": "Lorem Ipsum",
"subtitle": "sit amet"
},
{
"id": "5427ake0-eb27-1bcb-84ds-d374e2098dd3",
"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.",
"thumb": "https://source.unsplash.com/user/erondu/1600x900.jpg",
"title": "Perspiciatis",
"subtitle": "sed ut"
},
{
"id": "23g8f61f-9heb-4d3b-a8e4-0b22c31deb0e",
"description": "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.",
"thumb": "https://source.unsplash.com/user/erondu/1600x900.jpg",
"title": "Nemo Enim Ipsam",
"subtitle": "sit aspernatur"
},
{
"id": "6419ac9e-5718-4eee-af53-1d20cf58146b",
"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.",
"thumb": "https://source.unsplash.com/user/erondu/1600x900.jpg",
"title": "At Vero Eos",
"subtitle": "quos dolores"
}
]
}
thumbs.js
import React from 'react';
import { images } from '../../data/images.json';
export const Thumbs = () => {
return (
<>
<div className="thumb-container">
{images.map((data, key) => {
reutrn (
<div key={key}>
{data.thumb}
</div>
);
})}
</div>
</>
);
};
I also have a file that renders a .Thanks for reading!
You have return mispelled. That's the only error I can find in your code, I ran it in a brand new create-react-app app and it worked just fine. There could be an issue if you're not using a recent version of Webpack, but it would have to be a pretty old version to not have built in json loading. And here's my modified code, which is just showing the images rather than their URLs:
export const Thumbs = () => (
<div className="thumb-container">
{images.map((img, i) => <img src={img.thumb} key={i} />)}
</div>
)

Object output returning NAN [duplicate]

This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
Closed 3 years ago.
This is my code
const products =
[
{
"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",
"coefficient":2,
"price": () => 2000 * this.coefficient
},
{
"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",
"coefficient":3,
"price": () => 2000 * this.coefficient
},
]
I want to return the price depends on the coefficient, but when i excute
products[0].price() // return NaN
how can i fix that ?
Thanks.
This is due to the way that arrow functions handle the this scope. In this case, replacing the arrow function (() => this.something) with a traditional JS function (function() { return this.something; }) will solve your problem.
The this in an arrow function refers to the class scope, that is an empty object; in that case, yo refer to the the object scope you must use the full function syntax.
Try this:
products = [
{
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",
coefficient: 2,
price: function() {
return 2000 * this.coefficient;
}
},
{
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",
coff: 3,
price: function() {
return 2000 * this.coefficient;
}
}
];
console.log(products[0].price()) // 4000
console.log(products[1].price()) // 6000
For the arrow functions, value of this is not based on the object reference using which the function was executed. Rather it uses the this reference from the closure where it was declared. Check the documentation here on MDN. In your scenario this.coefficient would be undefined, which when multiplied with 2000 results in NaN.
You can change the arrow functions to proper functions if you need this to refer to the object reference on which price function was called. Changed code should be something like this:
products = [
{
"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",
"coefficient":2,
"price": function() { return 2000 * this.coefficient; }
}
];
You can use this :
const products =
[
{
"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",
"coefficient": 2,
price() {
return 2000 * this.coefficient
}
},
{
"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",
"coefficient": 3,
price() {
return 2000 * this.coefficient
}
},
]

Categories

Resources