How do you render objects from json - javascript

I need to render some images from some json that I am being given. The code looks like
class App extends React.Component {
componentDidMount() {
$.get(
"url"
data => {
});
}
render() {
return React.createElement("div", null, "hello");
}}
ReactDOM.render(React.createElement(App, null), document.body);
"url" is the json that I have passed in (but I do not want to make it public). It looks similar to this:
{
"total_count": null,
"_links": {
"self": {
"href": ""
},
"next": {
"href": ""
}
},
"_embedded": {
"showorks": [{
"id": "",
"slug": "",
"created_at": "",
"updated_at": "",
"title": "",
"category": "",
"medium": ",
"date": "",
"dimensions": {
"in": {
"text": "",
"height": 70.9,
"width": 70.9,
"depth": null,
"diameter": null
},
"cm": {
"text": "180.1 × 180.1 cm",
"height": 180.1,
"width": 180.1,
"depth": null,
"diameter": null
}
},
"published": true,
"website": "",
"signature": "",
"series": null,
"prov": "",
"lit": "",
"hist": "",
"isst": "",
"additional_information": "",
"image_rights": "",
"blurb": "",
"unique": false,
"maker": null,
"icon": ,
"inquire": false,
"acquire": false,
"share": true,
"message": null,
"sell":,
"image_versions": ,
"_links": {
"thumbnail": {
"href": ""
},
"image": {
"href": "",
"templated": true
},
"partner": {
"href": ""
},
"self": {
"href": ""
},
"link": {
"href": ""
},
"genes": {
"href": ""
},
"rar": {
"href": ""
},
"cim": {
"href": ""
},
"coll": {
"href": ""
}
},
"_embedded": {
"editions": []
}
}, {
"id": "",
I need the thumbnail for each id but I'm not sure how to iterate through the json to pull out each thumbnail in react/javascript

First, I totally recommend you to use JSX syntax to use React better. To do that, you will need a few Javascript Array helper function and some methods.
As you can see below:
class App extends React.Component
{
componentDidMount()
{
// We could imagine the incoming JSON data
// const exampleJson =
// {
// elements:
// [
// { href: 'example1', text: 'link value', style: { height: '10px' } },
// ],
// };
// This fetch API will help you to get JSON from URL like JQuery $.get
const exampleJson = fetch('http://example.com/links.json')
.then(function(response)
{
return response.json(); // get the values of JSON as string type
})
.then(function(myJson)
{
return JSON.stringify(myJson); // convert the JSON data to javascript object
});
this.setState(exampleJson); // it's like this.setState({ elements: [array values] });
console.log(exampleJson); // to do debug of your JSON data
}
render()
{
// we getting the elements array from state object
// with object spread operator
const { elements } = this.state;
// get values all of your json array
// loop values to do React element
// return all new values to use loopAndSaveElements variable
const loopAndSaveElements = elements
.map(({ text, ...otherProps}) => React.createElement('a', otherItems, text));
// send return div of React as loopAndSaveElements as array children
return React.createElement("div", null, loopAndSaveElements);
}
}
By the way, i didn't run the snippet of example. But i hope it give you an information.
ES6+ Sources:
const
Array map
spread syntax
JSX syntax
fetch API

Related

How do I update nested object by ID in VueJS

Issue:
I'm trying to update(axios.patch) active data from false to true of a nested object (children) by ID using axios patch request. I'm using vuejs as my frontend and json-server as my backend. Can anyone please help me.
Data:
{
"id": 3,
"icon": "store",
"name": "Store Management",
"children": [
{
"id": 1,
"name": "Tables",
"icon": "",
"active": false,
"path": "/store-management/tables"
},
{
"id": 2,
"name": "Discounts",
"icon": "",
"active": false,
"path": "/store-management/discounts"
},
{
"id": 3,
"name": "Surcharges",
"icon": "",
"active": false,
"path": "/store-management/surcharges"
},
{
"id": 4,
"name": "Promos",
"icon": "",
"active": false,
"path": "/store-management/promos"
}
],
"expanded": true,
"path": "",
"active": false,
"hasChildren": true
}
Function:
When I call the #click function the navigateChildren will execute and it needs to get the path of the nested object and at the same time update the active value to true or false.
async navigateChildren(id) {
try {
const menuChildren = await axios.get('http://localhost:3000/menu/3')
const menuChildrenList = menuChildren.data
const children = menuChildrenList.children[id - 1]
const inactive = await axios.patch(
'http://localhost:3000/menu/' + this.menuId,
{
active: false
}
)
console.log(inactive)
const active = await axios.patch('http://localhost:3000/menu/3', {
children: {
active: true
}
})
console.log(active)
const path = children.path
this.$store.commit('setMenuId', id)
this.$router.push(path)
console.log(children)
} catch (error) {
}
}
Many Thanks.

Generate a new Json specifying a selection of fields from another existent Json inside async/await

in my Vue app I have this piece of code:
async fetchCars() {
try {
let response = await fetch("https://cars.com/api/")
let cars = await response.json()
this.cars = cars
} catch (e) {
console.log(e)
}
}
{{ cars }} will return this:
{
"owner": "",
"place": ""
"cars": [
{
"model": "",
"make": "",
"color": "",
"features": [
{
"gear": "",
"roof": "",
"wheels": ""
}
]
}
However I would like to specify the fields to keep (not the ones to delete), and have:
{
"owner": "",
"cars": [
{
"model": "",
"make": "",
"features": [
{
"gear": "",
"roof": ""
}
]
}
]
I tried to play with .map() and Promise.all() but with no success.
Thanks
Maybe there are more pretty ways, I am not sure, but I am using nested maps and object destructuring here. You don't need Promise.all to map some values.
const mapped = [{
"owner": "",
"place": "",
"cars": [{
"model": "",
"make": "",
"color": "",
"features": [{
"gear": "",
"roof": "",
"wheels": ""
}]
}]
}].map(({
owner,
cars
}) => ({
owner,
cars: cars.map(({
model,
make,
features
}) => ({
model,
make,
features: features.map(({
gear,
roof
}) => ({
gear,
roof
}))
}))
}))
console.log(mapped)

Partial selection on Inner Join

I need select ony on field to services, look:
async find(): Promise<AccountEntity[]> {
const result = await this.repository
.createQueryBuilder("account")
.select(['account', 'accountServices', 'service.description'])
.leftJoinAndSelect("account.accountAndServices", "accountServices")
.leftJoinAndSelect("accountServices.service", "service")
.getMany();
return result === undefined ? null : result;
}
How to ? please.
I don't want null attributes to appear and I also want to choose which attributes to show
I need :
{
"message": "",
"success": true,
"data": [
{
"id": 1,
"name": "STONES TECNOLOGIA LTDA",
"accountAndServices": [
{
"service": {
"name": "Construção de uma casa",
},
"date_initial": "2021-08-01T07:39:18.000Z",
"date_final": "2021-08-01T07:39:20.000Z",
"value": "10.00",
"created_by": 1,
"is_active": true,
"id": 1,
"pay_day": 10,
"nfse": 0,
"created_at": "2021-08-01T07:39:27.000Z",
},
{
"service": {
"name": "Desenvolvimento de sistemas",
},
"date_initial": "2021-08-01T07:40:01.000Z",
"date_final": "2021-08-01T07:40:02.000Z",
"value": "20.00",
"created_by": 1,
"is_active": true,
"id": 2,
"pay_day": 20,
"nfse": 0,
"created_at": "2021-08-01T07:40:11.000Z",
}
]
}
],
"errors": null
}
I Need selection only field on entity join.
Select with innerJoin you must use addSelect(...).
The find function must not manipulate any data and should return an array of AccountEntity (empty if not found):
function find(): Promise<AccountEntity[]> {
return this.repository
.createQueryBuilder("a")
.innerJoin("account.accountAndServices", "as")
.innerJoin("accountServices.service", "s")
.select(['a.id', 'a.name', 'a.status'])
.addSelect(['as.date_initial', 'as.date_final', 'as.service_id', 'as.value', 'as.nfse', 'as.value', 'as.created_by', 'is_active', 'pay_day', 'created_at'])
.addSelect(['s.name'])
.getMany();
}
Note that to obtain the result from the function you must use await.
Moreover, surround it with try and catch for a better error handling.
Example:
try {
const accounts: AccountEntity[] = await find();
} catch(error) {
console.error(`Error: ${error}`);
}
To transform the array of AccountEntity to another object:
function transform(accounts?: AccountEntity[]) {
return {
message: "",
success: accounts !== undefined,
data: accounts,
errors: null
};
}

How to extract all Urls from Json object

Regardless of the JSON object structure (simple or complex) what would be the ideal method to extract all urls from the following object into an array to iterate over in Javascript?
{
"url": "https://example.com:443/-/media/images/site/info",
"data": [
{
"id": "da56fac6-6907-4055-96b8-f8427d4c64fd",
"title": "AAAA 2021",
"time": "",
"dateStart": "2021-03-01T08:00:00Z",
"dateEnd": "2021-12-31T15:00:00Z",
"address": "",
"geo": {
"longitude": "",
"latitude": "",
"mapExternalLink": ""
},
"price": "Free Admission",
"masonryImage": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"image": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"showDateInfo": false,
"showDateInfoOnListings": false,
"showTimeInfo": false,
"showTimeInfoOnListings": false,
"tags": [
{
"key": "Lifestyle",
"name": "Lifestyle"
}
],
"partnerName": "",
"sort_data": {
"recommended": 0,
"recent": 3,
"partner": 0,
"popular": 0
}
}
]
}
I would like to get the results in an array such as:
[
https://example.com:443/-/media/images/site/info,https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx, https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx
]
I gather that i would need to apply some regex to extract the urls but not sure how to treat the json object as string for regex processing?
I think the better and easier way is to stringfy given json into string and solve it by regex.
But still if you need to solve it by recursive, try the codes below:
const obj = {
url: "https://example.com:443/-/media/images/site/info",
data: [
{
id: "da56fac6-6907-4055-96b8-f8427d4c64fd",
title: "AAAA 2021",
time: "",
dateStart: "2021-03-01T08:00:00Z",
dateEnd: "2021-12-31T15:00:00Z",
address: "",
geo: {
longitude: "",
latitude: "",
mapExternalLink: "",
},
price: "Free Admission",
masonryImage:
"https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
image: "https://tw.yahoo.com",
showDateInfo: false,
showDateInfoOnListings: false,
showTimeInfo: false,
showTimeInfoOnListings: false,
tags: [
{
key: "Lifestyle",
name: "Lifestyle",
link: "https://www.google.com",
},
],
partnerName: "",
sort_data: {
recommended: 0,
recent: 3,
partner: 0,
popular: 0,
anotherObj: {
link: "https://www.github.com",
},
},
},
],
};
function getUrl(obj) {
const ary = [];
helper(obj, ary);
return ary;
}
function helper(item, ary) {
if (typeof item === "string" && isUrl(item)) {
ary.push(item);
return;
} else if (typeof item === "object") {
for (const k in item) {
helper(item[k], ary);
}
return;
}
return null;
}
function isUrl(str) {
if (typeof str !== "string") return false;
return /http|https/.test(str);
}
console.log(getUrl(obj));
But if you use this solution you need to transfer your json into js object
i'd agree to use a JSON parser, but if you want to do it with a regular expression, you might try this
console.log(JSON.stringify({
"url": "https://example.com:443/-/media/images/site/info",
"data": [{
"id": "da56fac6-6907-4055-96b8-f8427d4c64fd",
"title": "AAAA 2021",
"time": "",
"dateStart": "2021-03-01T08:00:00Z",
"dateEnd": "2021-12-31T15:00:00Z",
"address": "",
"geo": {
"longitude": "",
"latitude": "",
"mapExternalLink": ""
},
"price": "Free Admission",
"masonryImage": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"image": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"showDateInfo": false,
"showDateInfoOnListings": false,
"showTimeInfo": false,
"showTimeInfoOnListings": false,
"tags": [{
"key": "Lifestyle",
"name": "Lifestyle"
}],
"partnerName": "",
"sort_data": {
"recommended": 0,
"recent": 3,
"partner": 0,
"popular": 0
}
}]
}).match(/(?<=")https?:\/\/[^\"]+/g));
(?<=")https?:\/\/[^\"]+ basically finds patterns that start with a protocol scheme (http:// or https:// preceded by a " character) followed by anything that is not "

Json Structure- How to read this JSON structure in javascript?

Can anyone help me to fetch the comments value from the below json structure.
Actually i want the id(very first column after items) for which the no of comments is 0. I m able to read the id but unable to put the if condition (comment =0) return {id}
"data": {
"posts": {
"items": [
{
"id": ,
"content": {
"id": ,
"files": [],
"user_details": {
"firstname": "",
"lastname": ""
},
"comments": "",
"tags": [
"anonymous"
],
"likeCount": 0,
"group_details": {
"group_name": "",
"guid":
},
"propertytags": {
"empty": ""
},
"permalink": {
"link":
},
"isFollowed": ,
"followerCount": "",
"favorite": "",
"isLiked": ""
},
"contentType": "",
"group_details": {
"group_name": ,
"guid":
}
}
How to read comments value?????
data.posts.items[index].content.comments will give you the value of comments.
However to fetch the id based on comment value, you may use Array.filter() function.
let result = data.posts.items.filter(item => {
if (item.content.comments === "0") {
return item.id;
}
});
result will be an array of id for which the comments is 0.
Here is an example with the data you've shared JS Bin

Categories