Related
I have a JSON like this, how to get the value of StatusDescription? I tried many times but the result is undefined. Here is my JSON:
{
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
I'm using in my NodeJS app, like myapp.js, and console.log()
Try this
I stored your sample json in variable json
var json = {
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
Accessed it like below
console.log(json.data.items[0].origin_info.trackinfo[0].StatusDescription);
Items is an array and we took array element 0.
trackinfo again is an array and we took array element 0.
We can change array index or loop through and get required values.
You have to iterate through your items and trackinfo to get to StatusDescription. Try this one.
const data = {
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
const items = data.data.items.map(item => item)
const trackinfo = items.map(item => item.origin_info.trackinfo).flat()
console.log(trackinfo)
const statusDescription = trackinfo.map(trackinfo => trackinfo.StatusDescription)
console.log(statusDescription)
For reference I have zero javascript knowledge or any coding knowledge. I typically just hook up applications via IPASS applications that don't require any coding knowledge. However, I found out I need to inject some javascript into the application in order to avoid an error message.
I have the below JSON record.
I need to get rid of the empty array (sorry... if it is not an array but an object? Like I said, no javascript knowledge).
In the below code essentially what I want is to completely delete this line, because there is nothing inside the brackets and it is causing errors:
"lineitemsdata": []
Full JSON record below for reference
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [
{
"id": "5230410841",
"type": "company_to_deal"
}
]
}
},
"dealdata": [
{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [
{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}
],
"DealOwner": [
{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}
],
"NetSuiteCustomerID": 1745
}
Item inside object is called a property. If you (for some reason) have to include the property, but don't want it to have any value you can either set it's value to null or undefined.
I suspect I'm going to get criticized for this, but here is a quick and dirty way of removing this specific problem through string replacement. The 'right' way would be to break down your json into separte objects until you get to the level where the offending object lives, remove it, then rebuild it all back. For what it's worth, here's an alternative to that
let json = {
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [{
"id": "5230410841",
"type": "company_to_deal"
}]
}
},
"dealdata": [{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}],
"DealOwner": [{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}],
"NetSuiteCustomerID": 1745
}
json = JSON.stringify(json)
let strstart = json.indexOf('"lineitemsdata":[]');
let commapos = json.lastIndexOf(',', strstart);
json = json.substr(0, commapos) + " " + json.substr(commapos + 1);
json = json.replace('"lineitemsdata":[]', '');
json = JSON.parse(json)
console.log(json)
You can use this to strip any empty lineitems arrays from your json.
Assuming the reference to your record is json
for(dealIdx in json.dealdata) {
for (resultIdx in json.dealdata[dealIdx].associations["line items"].results) {
let lineItemsData = json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
if (lineItemsData != undefined && lineItemsData.length === 0 ) {
delete json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
}
}
}
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
This question already has an answer here:
Filter collection (array of objects) based on other array
(1 answer)
Closed 6 years ago.
I have an object and an array
{
"library_items":
[
{
"id": "23493",
"artifactID": "",
"title":"Physics Lecture",
"authors": [{
"name": "Don Johnson",
"artifactID": "",
"role": "author",
"roleID": ""
}],
"artifactType": "games",
"domain": {
"branch": "",
"description": "",
"branchInfo": {
"branch": "",
"subject": "Physics"
}
},
"type": {
"description": "",
"id": "",
"name": ""
}
},
{
"id": "23493",
"artifactID": "",
"title":"Chemistry Lecture",
"authors": [{
"name": "Don Johnson",
"artifactID": "",
"role": "author",
"roleID": ""
}],
"artifactType": "games",
"domain": {
"branch": "",
"description": "",
"branchInfo": {
"branch": "",
"subject": "Chemistry"
}
},
"type": {
"description": "",
"id": "",
"name": ""
}
}
]
}
I have another array
var subjects = ['Physics', 'Biology', 'Mathematics']
how do I filter the Object using the array values in "subjects"?. I mean I want to get items from the object which have subject corresponding to any of the array values.
Basically, making use of filter and indexOf methods.
filter Make use of this method to filter the array as per the matching criteria as defined in the callback function.
indexOf To check if the Array contains a value.
Note: There is another method includes which can check for existence of an element in an array, which is part of ES7 draft but it is not supported by many browsers.
var items = {
"library_items":
[
{
"id": "23453",
"artifactID": "",
"title":"Physics Basics",
"subject": "Physics"
},
{
"id": "23453",
"artifactID": "",
"title":"Chemistry Basics",
"subject": "Chemistry"
}
]
};
var subjects = ['Physics', 'Biology', 'Mathematics'];
var filtered = items.library_items.filter((x) => subjects.indexOf(x.subject) > -1);
console.log(filtered);
You could use Array#filter and Array#includes
var items = { library_items: [{ id: "23453", artifactID: "", title: "Physics Basics", subject: "Physics" }, { id: "23453", artifactID: "", title:"Chemistry Basics", subject: "Chemistry" }] },
subjects = ['Physics', 'Biology', 'Mathematics'],
filtered = items.library_items.filter(x => subjects.includes(x.subject));
console.log(filtered);
I use lodash (https://lodash.com/docs) in every project. They have build a massive array of methods and wrappers that will make your live much easier.
var items = {
"library_items":
[
{
"id": "23453",
"artifactID": "",
"title":"Physics Basics",
"subject": "Physics"
},
{
"id": "23453",
"artifactID": "",
"title":"Chemistry Basics",
"subject": "Biology"
}
]
};
var subjects = ['Physics', 'Physics', 'Mathematics'];
_.find(items["library_items"], function(o) {
return subjects.indexOf(o.subject) > -1;
});
If you do not want to install additional packages I'd go with Agalo's answer!
If performance is important to you. I would suggest another approach to you.
With filter and indexOf(or includes) your performance of the algorithm is O(n*m). For each library item you need to go through each subject.
If you create a simple hash table from subjects array first you can archive O(n+m). First, you go through each subject and write it to the hash table then for each library item you can check with O(1)(because of the hash table) whether you need that item.
Here is the code example:
var items = {
"library_items":
[
{
"id": "23453",
"artifactID": "",
"title":"Physics Basics",
"subject": "Physics"
},
{
"id": "23453",
"artifactID": "",
"title":"Chemistry Basics",
"subject": "Chemistry"
}
]
};
var subjects = ['Physics', 'Biology', 'Mathematics'];
var allSubjects = {};
subjects.forEach(s => allSubjects[s] = true);
var filtered = items.library_items.filter(x => allSubjects[x.subject]);
console.log(filtered);
result = obj.library_items.filter(o => subjects.indexOf(o.subject) > -1)
I am having some troubles with looping through a JSON structure through jQuery,
Here is my JSON data:
{
"suppliers": [
{
"Supplier": {
"id": "5704ebeb-e5e0-4779-aef4-16210a00020f",
"name": "Gillmans",
"mobile": "",
"office_telephone": "00000",
"ooh_contact": "00000",
"fax_number": "",
"address_line_1": "St Oswalds Road",
"address_line_2": "Gloucester",
"address_line_3": "",
"address_line_4": "",
"postcode": "GL1 2SG",
"email": "email#example.com",
"contact": "",
"position": "",
"aov": "180.00",
"engineer": false,
"cc_on_new_job_emails": true,
"can_add_quotes": false,
"notes": "",
"status": "1",
"created": "2016-04-06 11:58:51",
"modified": "2016-07-27 11:23:01",
"status_text": "Active",
"engineer_text": "No",
"cc_on_new_job_emails_text": "Yes"
},
"Trade": [],
"PostcodeArea": []
},
{
"Supplier": {
"id": "571e390f-91e8-4745-8f78-168b0a00020f",
"name": "Kings",
"mobile": "",
"office_telephone": "00000",
"ooh_contact": "0000",
"fax_number": "",
"address_line_1": "",
"address_line_2": "",
"address_line_3": "",
"address_line_4": "",
"postcode": "",
"email": "",
"contact": "",
"position": "Account Manager; Joanne Brook",
"aov": null,
"engineer": false,
"cc_on_new_job_emails": false,
"can_add_quotes": false,
"notes": "",
"status": "1",
"created": "2016-04-25 16:34:39",
"modified": "2016-07-08 15:22:15",
"status_text": "Active",
"engineer_text": "No",
"cc_on_new_job_emails_text": "No"
},
"Trade": [],
"PostcodeArea": []
}
]
}
This JSON is returned from my AJAX call in a variable called data. data is a Javascript object, i.e. it's already been parsed by the ajax call.
I am trying to loop through this JSON data and grab the name and id properties. Here is how I have done it:
$.each(data, function(k, v) {
$.each(this, function(key, val) {
$.each(this, function(key2, val2) {
$.each(this, function(key3, val3) {
if(key3 == 'name')
{
alert(val3);
}
});
});
});
});
This will print all of the name values but obviously this is quite a messy way and I was wondering if there is an easier way I can get the name and id properties of this structure and store them in variables?
You can deal with the JSON as an object if you parse it:
//this has already been done by the ajax call by the sounds of it.
//var jsObj = JSON.parse(data);
//suppliers is an array now ([]), so loop it
$.each(data.suppliers, function(index, value){
//value is a supplier object ({}) so you can acces it's properties directly
alert(value.Supplier.name);
});
$.each(data.suppliers, function(){
alert(this.Supplier.id);
});
Try this :
var data = {
"suppliers":[
{
"Supplier":{
"id":"5704ebeb-e5e0-4779-aef4-16210a00020f",
"name":"Gillmans"
},
"Trade":[
],
"PostcodeArea":[
]
},
{
"Supplier":{
"id":"571e390f-91e8-4745-8f78-168b0a00020f",
"name":"Kings"
},
"Trade":[
],
"PostcodeArea":[
]
}
]
}
$.each(data.suppliers, function(k, v) {
alert(this.Supplier.id);
})