What I am trying to do exceeds my knowledge. Thank you all for your time and help, it is a great pleasure to have the support of such a large community of great developers.
The problem
I need to loop over an object (JSON response) to determine which data is true and then edit the html with the results.
json object is:
var data = {
"total": 4,
"limit": 50,
"questions": [{
"date_created": "2015-06-29T18:24:25.000-04:00",
"item_id": "MLA567045929",
"seller_id": 186626557,
"status": "UNANSWERED",
"text": "Pregunta de Testeo, user 2.",
"id": 3612747353,
"deleted_from_listing": false,
"hold": false,
"answer": null,
"from": {
"id": 186625262,
"answered_questions": 0
}
}, {
"date_created": "2015-06-29T18:30:16.000-04:00",
"item_id": "MLA567045929",
"seller_id": 186626557,
"status": "UNANSWERED",
"text": "Lorem ipsum dolor sit amet",
"id": 3612938882,
"deleted_from_listing": false,
"hold": false,
"answer": null,
"from": {
"id": 186625262,
"answered_questions": 0
}
}, {
"date_created": "2015-06-29T18:30:35.000-04:00",
"item_id": "MLA567045929",
"seller_id": 186626557,
"status": "UNANSWERED",
"text": "an est odio timeam quaerendum",
"id": 3612752695,
"deleted_from_listing": false,
"hold": false,
"answer": null,
"from": {
"id": 186625262,
"answered_questions": 0
}
}, {
"date_created": "2015-06-29T18:31:32.000-04:00",
"item_id": "MLA567045929",
"seller_id": 186626557,
"status": "ANSWERED",
"text": "Responder esta pregunta",
"id": 3612753455,
"deleted_from_listing": false,
"hold": false,
"answer": {
"text": "Pregunta respondida",
"status": "ACTIVE",
"date_created": "2015-06-29T18:31:58.000-04:00"
},
"from": {
"id": 186625262,
"answered_questions": 1
}
}],
"filters": {
"limit": 50,
"offset": 0,
"is_admin": false,
"sorts": [],
"caller": 186626557,
"seller": "186626557"
},
"available_filters": [{
"id": "item",
"name": "Item",
"type": "text"
}, {
"id": "from",
"name": "From user id",
"type": "number"
}, {
"id": "totalDivisions",
"name": "total divisions",
"type": "number"
}, {
"id": "division",
"name": "Division",
"type": "number"
}, {
"id": "status",
"name": "Status",
"type": "text",
"values": ["BANNED", "CLOSED_UNANSWERED", "DELETED", "DISABLED", "UNDER_REVIEW"]
}],
"available_sorts": ["item_id", "from_id", "date_created", "seller_id"]
};
The result I'm looking for is:
Of the data object, I need to extract questions with the status unanswered and the id field associated with these unanswered questions.
"questions1":[{ "status" : "UNANSWERED",
"id" : 3612747353}],
"questions2":[{ "status" : "UNANSWERED",
"id" : 3612938882}],
...
Based on what I've searched, I've tried with loops, for in, and each without success.
Any suggestions or ideas on how I could achieve the desired result? I need to apply this example to several objects.
Try some handy list processing functions to simplify it conceptually. The filter and map functions will help. The function I provided to filter tells it to only let through items that meet the condition of having an unanswered status. The function I provided to map turned all the objects that came out of filter into just their ids.
data["questions"].filter(function(obj) {
return obj["status"] === "UNANSWERED";
}).map(function(obj) {
return obj["id"];
});
var results = [];
for (var question in data.questions) {
if (data.questions[question].status === "UNANSWERED") {
results.push({
"status" : data.questions[question].status,
"id" : data.questions[question].id
});
}
}
// Now results contains an array of unanswered questions,
// with just their status & id.
You can just loop through the questions and save the ids you want to an array:
var questions = data.questions;
var unanswered = [];
for(var i = 0, len = questions.length; i < len; i++) {
if(questions[i].status === 'UNANSWERED') {
unanswered.push(questions[i].id);
}
}
unanswered will be an array of unanswered question ids. You don't need to save the status; you know they are all 'UNANSWERED'.
Related
In order to check from my frontend application if there is or not a PDF I want to search into my nested object 'translations' for the field named "pdf_url".
{
"id": 118,
"name": "MIXY",
"thumbnail": null,
"translations": [
{
"field": "name",
"lang": "it",
"text": "MIXY"
},
{
"field": "name",
"lang": "en",
"text": "MIXY"
},
{
"field": "thumbnail",
"lang": "en",
"text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypng.png"
},
{
"field": "pdf_url",
"lang": "en",
"text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypdf.pdf"
}
]
},
{
"id": 119,
"name": "CITY",
"thumbnail": null,
"translations": [
{
"field": "pdf_url",
"lang": "en",
"text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypdf.pdf"
},
{
"field": "name",
"lang": "it",
"text": "CITY"
},
{
"field": "thumbnail",
"lang": "en",
"text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypng.png"
},
{
"field": "name",
"lang": "en",
"text": "CITY"
},
The problem I am dealing with i that for every cardObject (id: 118, 119) the pdf_url can be in position 0, 1, 2, 3 or n inside that the translations array. So when I try to access it like this, for example
cardObject?.['translations']?.[2]?.['text']
I am not always sure I check the "pdf_url" of my card. I would firstly check is the object has "pdf_url" key value using
card?.['translations'].hasOwnProperty('pdf_url')
and then? Should I loop over the translations array of objects? Is there a simple way to "reduce" or even better group my data?
You can use Array.prototype.find to find the first object in the array that has a field property with the value pdf_url.
const pdfUrl = cardObject.translations.find(translation => translation.field === 'pdf_url');
console.log(pdfUrl.text);
// /var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypdf.pdf
How can i updated isCompleted property to true on onClick. I can only access moduleContent id from route e.g.- "id": "cr1mod1content1". How can i update isCompleted property to true by only matching this id. Note: i'm using react/nextJS for this project.
here is my json data structure.
[
{
"id": 1,
"progress": 0,
"title": "Python Basics for Data Science",
"modules": [
{
"id": "cr1mod1",
"title": "Module 1- Python Basics",
"moduleContent": [
{
"type": "html",
"id": "cr1mod1content1",
"title": "Module Introduction and Learning Objectives",
"content": " <p> This module teaches the basics of Python and begins </p>",
"quizContent": [],
"isCompleted": false
},
{
"type": "video",
"id": "cr1mod1content2",
"title": "Video: Types (3:02)",
"content": "https://vimeo.com/23",
"quizContent": [],
"isCompleted": false
},
{
"type": "quiz",
"id": "cr1mod1content3",
"title": "Practice Quiz: Types",
"content": "",
"quizContent": [],
"isCompleted": false
}
]
},
{
"id": "cr1mod2",
"title": "Module 2 - Python Data Structures",
"moduleContent": [
{
"type": "html",
"id": "cr1mod2content1",
"title": "Module Introduction and Learning Objectives",
"content": " <p>This module begins a journey into Python data structure</p> ",
"quizContent": [],
"isCompleted": false
},
{
"type": "video",
"id": "cr1mod2content2",
"title": "Video: Types (8:31)",
"content": "https://vimeo.com/1",
"quizContent": [],
"isCompleted": false
},
{
"type": "quiz",
"id": "cr1mod2content3",
"title": "Practice Quiz: Types",
"content": "",
"quizContent": [],
"isCompleted": false
}
]
}
]
}
]
You can reach this in this way:
const arr = declare Your JSON array there
const id = 'cr1mod2content3'
for(const module of arr[0].modules) {
for(const item of module.moduleContent) {
if(item.id === id) item.isCompleted = true
}
}
Take into account that if your root JSON array may contain several elements, you will have to wrap the cycle with one more (root) iteration.
You can use some() of array for checking and update
const data = [
{
"id": 1,
"progress": 0,
"title": "Python Basics for Data Science",
"modules": [
{
"id": "cr1mod1",
"title": "Module 1- Python Basics",
"moduleContent": [
{
"type": "html",
"id": "cr1mod1content1",
"title": "Module Introduction and Learning Objectives",
"content": " <p> This module teaches the basics of Python and begins </p>",
"quizContent": [],
"isCompleted": false
},
{
"type": "video",
"id": "cr1mod1content2",
"title": "Video: Types (3:02)",
"content": "https://vimeo.com/23",
"quizContent": [],
"isCompleted": false
},
{
"type": "quiz",
"id": "cr1mod1content3",
"title": "Practice Quiz: Types",
"content": "",
"quizContent": [],
"isCompleted": false
}
]
},
{
"id": "cr1mod2",
"title": "Module 2 - Python Data Structures",
"moduleContent": [
{
"type": "html",
"id": "cr1mod2content1",
"title": "Module Introduction and Learning Objectives",
"content": " <p>This module begins a journey into Python data structure</p> ",
"quizContent": [],
"isCompleted": false
},
{
"type": "video",
"id": "cr1mod2content2",
"title": "Video: Types (8:31)",
"content": "https://vimeo.com/1",
"quizContent": [],
"isCompleted": false
},
{
"type": "quiz",
"id": "cr1mod2content3",
"title": "Practice Quiz: Types",
"content": "",
"quizContent": [],
"isCompleted": false
}
]
}
]
}
]
const updateData = (arr, idFilter) => {
arr.some(({modules}) => {
modules.some(({moduleContent}) => {
moduleContent.some(ele => {
if (ele.id === idFilter) {
return ele.isCompleted = true
}
return false
})
})
})
}
updateData(data, 'cr1mod1content1')
console.log(data)
You can use map double times to update
data[0].modules.map(item => item.moduleContent.map(obj => {
if (obj.id === "cr1mod1content1") {
obj.isCompleted = true
}
}));
I am trying to set a variable from following phone number with value: “+33652556777” (index 4 in JSON attached below) which is the last object in contacts (index 4).
To do so is pretty simple:
let jsonData = pm.response.json();
console.log (jsonData.contacts[4].phone_numbers[0].value)
const PhoneNumber = jsonData.contacts[4].phone_numbers[0].value
pm.environment.set("Jacky", PhoneNumber);
Since I have to use different query parameters to filter by eg. created_at=asc, desc, the property of the phone_numbers order might change index number and I won’t be able to fetch desire phone number "+33652556777” instead it will set a different phone number which I cannot allow.
I know there is way to fetch our number and make it variable for next requests, which is iterating over properties or keys in the object “ for….in or for…of ” but for some reason I cannot achieve it.
What I could achieve is to get through first object “contacts” but impossible to get to its nested array “phone_numbers”. Here is how I did it:
let jsonData = pm.response.json();
let contact;
for (let filter of jsonData.contacts){
if (filter.last_name == "Rowland"){
contact = filter;
}}
console.log (contact);
Could you please help?
Here goes the JSON body response:
{
"contacts": [
{
"id": 11121211,
"direct_link": "https://example.example",
"first_name": "test1",
"last_name": "test",
"company_name": "test",
"information": null,
"is_shared": true,
"created_at": 1582798926,
"updated_at": 1582798926,
"emails": [],
"phone_numbers": [
{
"id": 60065270,
"label": "Work",
"value": "+33134567666"
}
]
},
{
"id": 22222222,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686067,
"updated_at": 1583686067,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567899"
}
]
},
{
"id": 33333564,
"direct_link": "https://example.example",
"first_name": "Jessica",
"last_name": "Biel",
"company_name": "N-Sync",
"information": null,
"is_shared": true,
"created_at": 1583686086,
"updated_at": 1583686086,
"emails": [],
"phone_numbers": []
},
{
"id": 45678901,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686105,
"updated_at": 1583686105,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567333"
}
]
},
{
"id": 56789123,
"direct_link": "https://example.example",
"first_name": "Jacky",
"last_name": "Rowland",
"company_name": "Test Company1",
"information": "",
"is_shared": true,
"created_at": 1583745888,
"updated_at": 1608556499,
"emails": [
{
"id": 76594398,
"label": "Work",
"value": "mandatory_field#example.com"
}
],
"phone_numbers": [
{
"id": 60650277,
"label": "Mobile",
"value": "+33652556777"
}
]
}
],
"meta": {
"count": 6,
"total": 241,
"current_page": 1,
"per_page": 5,
"next_page_link": "https://example.example",
"previous_page_link": null
}
}
You could use something basic like this:
_.each(pm.response.json().contacts, (contact) => {
if(contact.last_name === "Rowland") {
pm.environment.set(`${contact.first_name}_${contact.last_name}_number`, contact.phone_numbers[0].value)
}
})
There are probably better and more performant ways to do this but if you just want to set a variable for that contact, no matter where they are in the response - This would work :D
you can use forEach or _.each as danny mentioned to get all numbers else use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers[0].value)
use array.find to find the contact with first_name jacky adn then get phone_number[0].value from it.
if you want all numbers from that array then use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers.map((a)=>a.value))
here we map the result to get only the numbers from phone_number array.
is it what you looking for !?
I have a small question about knockout.
I have made a viewmodel
that looks like this (there are more subitems then Actions)
{
"PlatformSettings": [
{
"Actions": [
{
"Selected": false,
"Text": "None",
"Value": "None"
},
{
"Selected": true,
"Text": "Validation1",
"Value": "Validation1"
},
{
"Selected": true,
"Text": "Validation2",
"Value": "Validation2"
},
{
"Selected": true,
"Text": "Validation3",
"Value": "Validation3"
}
],
"Platform": {
"Id": "89",
"Description": "ONTWIKKELB"
}
},{
"Actions": [
{
"Selected": false,
"Text": "None",
"Value": "None"
},
{
"Selected": true,
"Text": "Validation1",
"Value": "Validation1"
},
{
"Selected": true,
"Text": "Validation2",
"Value": "Validation2"
},
{
"Selected": true,
"Text": "Validation3",
"Value": "Validation3"
}
],
"Platform": {
"Id": "89",
"Description": "ONTWIKKELB"
}
}
It works fine, but when i edit the checkboxes in my view and map them
self.Save = function(validate) {
var unmapped = ko.mapping.toJSON(self);
******
return false;
};
unmapped doesn't show the changes. And all the select values still show as on page load. I tried to make observable arrays, but the past 2 hours, but i can't figure it out.
Many thanks
Making the array observable will notify subscribers on add\remove. Making the "selected" property of each element observable will notify subscribers when it changes and allow 2 way binding.
So basically, make the selected property of each array element an observable too.
I'm trying to use the jQuery UI Autocomplete widget with a custom JSON feed I'm getting back from an API, which is formatted as follows:
{
"SearchTerm": "ches",
"HasDirectCountyHit": false,
"DirectCountyHitId": null,
"HasDirectLocationHit": false,
"DirectLocationHitId": null,
"Developments": [
{
"Id": "45339ae3e55a",
"Label": "Chestnut Walk, Bilston",
"Url": "/developments/chestnut-walk-bilston"
},
{
"Id": "4835f52e053a",
"Label": "Crown Park, Chester",
"Url": "/developments/crown-park-chester"
},
{
"Id": "757964964cc6",
"Label": "The Birches, West Timperley",
"Url": "/developments/the-birches-west-timperley"
}
],
"Counties": [
{
"Id": "7",
"Label": "Cheshire",
"Url": "/search?cid=7"
},
{
"Id": "24",
"Label": "Greater Manchester",
"Url": "/search?cid=24"
}
],
"Locations": [
{
"Id": "12061",
"Label": "Cheselbourne, Dorset (DT2 7)",
"Url": "/search?lid=12061"
},
{
"Id": "12062",
"Label": "Chesham, Buckinghamshire (HP5 1)",
"Url": "/search?lid=12062"
},
{
"Id": "12063",
"Label": "Chesham, Greater Manchester (BL9 6)",
"Url": "/search?lid=12063"
},
{
"Id": "12064",
"Label": "Chesham Bois, Buckinghamshire (HP6 5)",
"Url": "/search?lid=12064"
},
{
"Id": "12065",
"Label": "Cheshunt, Hertfordshire (EN8 9)",
"Url": "/search?lid=12065"
},
{
"Id": "12066",
"Label": "Chesley, Kent (ME9 7)",
"Url": "/search?lid=12066"
},
{
"Id": "12067",
"Label": "Cheslyn Hay, Staffordshire (WS6 7)",
"Url": "/search?lid=12067"
},
{
"Id": "12068",
"Label": "Chessetts Wood, Warwickshire (B94 6)",
"Url": "/search?lid=12068"
},
{
"Id": "12069",
"Label": "Chessington, Kingston upon Thames - Greater London (KT9 2)",
"Url": "/search?lid=12069"
},
{
"Id": "12070",
"Label": "Chessmount, Buckinghamshire (HP5 1)",
"Url": "/search?lid=12070"
}
]
}
The API I'm calling returns results based on my search term, so I know that all of the results in the nested objects are matches - my problem is how to access these objects ('Developments', 'Counties' and 'Locations') so that the autocomplete widget can pick up the 'Label' values?
Thanks,
Robin
Ok - here's what you can do:
//put all the keys you want to pull out of your json in an array
var props = [
"Locations", "Counties", "Developments"
];
//empty array for your autocomplete
var labels = [];
//loop thru all the properties you care about
$.each(props, function () {
$.each(source[this], function () {
//and pull out all the labels and add them to the labels array
labels.push(this.Label)
});
});
$("#autocomplete").autocomplete({
source: labels
});
and to see it all in action I created a quick fiddle
http://jsfiddle.net/fr5yb3n0/