Search array parts by partial in some property - javascript

I have this kind of object in typescript
const photos =
{
"albumId": "1",
"title": "quidem molestiae enim",
"created": "1",
"photos": [
{
"id": "1",
"title": "sunset",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
{
"id": "2",
"title": "today is sunshine",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796"
},
{
"id": "3",
"title": "test",
"url": "https://via.placeholder.com/600/24f355",
"thumbnailUrl": "https://via.placeholder.com/150/24f355"
}
]
}
I need to push out all values that are not find in string, search in performed in photos.photos.title.
Here is example, lets say i have a string like this
const searchText = 'sun';
I need to serach inside photos.photos.title and remove all photos.photos that does not contais part of that word.My ne photos should look like this
const photos =
{
"albumId": "1",
"title": "quidem molestiae enim",
"created": "1",
"photos": [
{
"id": "1",
"title": "sunset",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
{
"id": "2",
"title": "today is sunshine",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796"
}
]
}
You will see that all remaining photos member is left, because in title they having a part of word sun
I dont know how even to start, i know i can do find, but i need to search only part of the word not entire word? It can not just be last memmber of the array, the array is much bigger :(

You can use filter() on photos.photos and check that if title contains 'sun' using includes()
const photos = { "albumId": "1", "title": "quidem molestiae enim", "created": "1", "photos": [ { "id": "1", "title": "sunset", "url": "https://via.placeholder.com/600/92c952", "thumbnailUrl": "https://via.placeholder.com/150/92c952" }, { "id": "2", "title": "today is sunshine", "url": "https://via.placeholder.com/600/771796", "thumbnailUrl": "https://via.placeholder.com/150/771796" }, { "id": "3", "title": "test", "url": "https://via.placeholder.com/600/24f355", "thumbnailUrl": "https://via.placeholder.com/150/24f355" } ] }
let str = "sun"
photos.photos = photos.photos.filter(x => x.title.includes(str))
console.log(photos)

Related

JSON to HTML page for name and image as output

Can somebody help me to get the Name with his associated image from the following json.
Code should be in HTML or JS, as I am a backend developer and not able to figure out this.
The JSON:
{
"boardMembers": [
{
"id": "18706279",
"name": "Monique R Herena",
"thumbnail": null,
"title": "Chief Colleague Experience Officer",
"slug": "18706279-monique-r-herena",
"webVisibility": true
},
{
"id": "19676689",
"name": "Elizabeth Rutledge",
"thumbnail": {
"url": "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iABmk_sWUnY4/v3/80x80.png",
"alt": null
},
"title": "Chief Marketing Officer",
"slug": "19676689-elizabeth-rutledge",
"webVisibility": true
},
{
"id": "18784925",
"name": "Tangela Richter",
"thumbnail": {
"url": "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iKYkW0FlMRW4/v3/80x80.png",
"alt": null
},
"title": "Chief Governance Ofcr/Secy",
"slug": "18784925-tangela-richter",
"webVisibility": true
},
{
"id": "15024090",
"name": "Laureen E Seeger",
"thumbnail": {
"url": "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iiw0z.pdTRbE/v1/80x80.jpg",
"alt": "LAUREEN E SEEGER"
},
"title": "Chief Legal Officer",
"slug": "15024090-laureen-e-seeger",
"webVisibility": true
},
{
"id": "21336581",
"name": "Jennifer Skyler",
"thumbnail": null,
"title": "Chief Corporate Affairs Officer",
"slug": "21336581-jennifer-skyler",
"webVisibility": true
},
{
"id": "19676686",
"name": "Raymond Joabar",
"thumbnail": null,
"title": "Pres:Global Risk/CRO",
"slug": "19676686-raymond-joabar",
"webVisibility": true
},
{
"id": "15365626",
"name": "Douglas E Buckminster",
"thumbnail": null,
"title": "Group Pres:Global Consumer",
"slug": "15365626-douglas-e-buckminster",
"webVisibility": true
},
{
"id": "16654781",
"name": "Anna Marrs",
"thumbnail": {
"url": "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iNFzMiuYiRGY/v3/80x80.png",
"alt": null
},
"title": "Pres:Global Commercial Svcs",
"slug": "16654781-anna-marrs",
"webVisibility": true
},
{
"id": "16804630",
"name": "Denise Pickett",
"thumbnail": {
"url": "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iReOY_ZB0dOI/v2/80x80.png",
"alt": null
},
"title": "Pres:Global Services Group",
"slug": "16804630-denise-pickett",
"webVisibility": true
},
{
"id": "6832356",
"name": "Anre D Williams",
"thumbnail": {
"url": "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iJ5kSc7LL.3Y/v2/80x80.png",
"alt": null
},
"title": "Pres:Global Merchant & Network Svcs",
"slug": "6832356-anre-d-williams",
"webVisibility": true
},
{
"id": "3221610",
"name": "Jeffrey C Campbell \"Jeff\"",
"thumbnail": {
"url": " ",
"alt": "35000014"
},
"title": "Exec VP/CFO",
"slug": "3221610-jeffrey-c-campbell",
"webVisibility": true
},
{
"id": "16733751",
"name": "Marc D Gordon",
"thumbnail": {
"url": " ",
"alt": null
},
"title": "Exec VP/CIO",
"slug": "16733751-marc-d-gordon",
"webVisibility": true
},
{
"id": "21531045",
"name": "Jessica Lieberman Quinn",
"thumbnail": null,
"title": "Exec VP/Controller",
"slug": "21531045-jessica-lieberman-quinn",
"webVisibility": true
},
{
"id": "19863566",
"name": "Alan P Gallo",
"thumbnail": {
"url": " ",
"alt": null
},
"title": "Exec VP:Internal Audit/Chief Audit Exec",
"slug": "19863566-alan-p-gallo",
"webVisibility": true
},
{
"id": "16310906",
"name": "Vivian Zhou",
"thumbnail": null,
"title": "Senior VP/Head:Investor Relations",
"slug": "16310906-vivian-zhou",
"webVisibility": false
}
],
"totalExecutives": 17
}
Welcome to the front-end world! First, HTML IS NOT a programming language, it is a Markup Language. You need to use JavaScript to do that, not HTML.
You need to parse the string into an object and iterate each "member" on the object list to get this Name and Photo. I wrote a JavaScript version and a PHP version for comparison.
If you're using JavaScript:
Parse the string into JavaScript object ("JSON.parse" function)
Iterate items in "boardMembers" list
Get those values
CODE:
//Your string
let stringToParse = '<your string here>'
//Converting your string to object
let convertedToObject = JSON.parse(stringToParse);
//Getting the boardMembers list from your parsed object
let listBoardMembers = convertedToObject.boardMembers;
//Creating Elements on HTML (creating a Paragraph with the received data and a container for the list of members). *Notice: I've created a "DIV" (container) with a unique ID ("listMembers"). This is important because when I start to iterate the members I will add them inside the container, and for that, I need to reference it using an ID.*
document.body.innerHTML = `<p> Received String: ${stringToParse}</p>`;
document.body.innerHTML += `<div id="listMembers"></div>`;
//Iterating the list of boardMembers using this length;
for (let i = 0; i < listBoardMembers.length; i++) {
let member = listOfMembers[i];
let memberName = member.name;
let memberImageURL = '';
// Verify if the user has thumbnail
if (member.thumbnail !== null){
memberImageURL = member.thumbnail.url;
}
//Adding this member to the member's container, using the container ID, that we created previously.
document.getElementById('listMembers').innerHTML += `
<div style="display: flex;">
<img src="${memberImageURL}">
<h1>${memberName}</h1>
</div>
`;
}
Best regards,

What is the best way to replace text in json?

So I have a bunch of JSON data and it contains a few fields. for example:
[{
"id": "XXX",
"version": 1,
"head": {
"text": "Main title",
"sub": {
"value": "next"
},
"place": "secondary"
},
"body": [{
"id": "XXX1",
"info": "three little birds",
"extended": {
"spl": {
"text": "song",
"type": {
"value": "a"
}
}
}
},
{
"id": "XXX2",
"info": [
"how are you?"
],
"extended": {
"spl": {
"text": "just",
"non-type": {
"value": "abc"
}
}
}
}
]
}]
what I'm trying to do is kind of conversion table (from a different JSON file)
if a field has the value 'a' replace it with 'some other text..' etc.
I have a service for the JSON pipeline, so I guess this is the right place to do the replacement.
so for this example, I have the JSON above and in my conversion table I have the following terms:
next: forward,
song: music,
a: option1,
just: from
etc...
What you are looking for can be achieved with templates. Replace the variable sections with some specific markers that you can find and replace from some external tools such as perl or sed.
For example, you could have a template.json with something like this:
...
"type": {
"value": "##VALUE##"
}
...
Then when you need the actual JSON, you could pass this though an intermediate script that replaces these templates with actual data.
cat template.json | sed -e 's/##VALUE##/my_value/' > target.json
Alternatively, with Perl:
cat template.json | perl -pi -e 's:\#\#VALUE\#\#:my_value:' > target.json
The best way is to parse it, replace the text in the object, and then stringify it.
The next best way is to use a regular expression.
In this example, I catch exceptions if path cannot be indexed, and use ['type'] instead of .type so it will scale to indexing 'non-type' if you wish.
const data = `[{
"id": "XXX",
"version": 1,
"head": {
"text": "Main title",
"sub": {
"value": "next"
},
"place": "secondary"
},
"body": [{
"id": "XXX1",
"info": "three little birds",
"extended": {
"spl": {
"text": "song",
"type": {
"value": "a"
}
}
}
},
{
"id": "XXX2",
"info": [
"how are you?"
],
"extended": {
"spl": {
"text": "just",
"non-type": {
"value": "abc"
}
}
}
}
]
}]
`
const o = JSON.parse(data)
o[0].body.forEach(b => {
try {
if (b.extended.spl['type'].value === 'a') {
b.extended.spl['type'].value = 'CHANGED'
}
} catch (e) {}
})
const newData = JSON.stringify(o, null, 2)
console.log(newData)
A string replace approach will work if you know and can rely on your source conforming, such as the only "value" is inside "type"
const data = `[{
"id": "XXX",
"version": 1,
"head": {
"text": "Main title",
"sub": {
"value": "next"
},
"place": "secondary"
},
"body": [{
"id": "XXX1",
"info": "three little birds",
"extended": {
"spl": {
"text": "song",
"type": {
"value": "a"
}
}
}
},
{
"id": "XXX2",
"info": [
"how are you?"
],
"extended": {
"spl": {
"text": "just",
"non-type": {
"value": "abc"
}
}
}
}
]
}]
`
const newData = data.replace(/"value": "a"/g, '"value": "NEWVALUE"')
console.log(newData)

how to remove this object from array inside of object in array?

I am not sure how to form this question, but I will do my best.
I don't know how to remove object by _id from 'list:' part.
So, I have one array, and inside of that array I have list of objects,inside of these objects I have again array with objects, so I want to remove one object from that last array, how I can do that?
Cannot fix it for 2 days, I'm stucked!
Thanks!
[
{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [
{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [
{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
]
Using Vanilla JS:
function findAndRemove(data, id) {
data.forEach(function(obj) { // Loop through each object in outer array
obj.list = obj.list.filter(function(o) { // Filter out the object with unwanted id, in inner array
return o._id != id;
});
});
}
var data = [{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
];
// Empty almost all of list, except middle one
findAndRemove(data, "599a1322bf50847b0972a384");
findAndRemove(data, "599a1322bf50847b0972a386");
findAndRemove(data, "599a12fdbf50847b0972a2a5");
findAndRemove(data, "599a12fdbf50847b0972a2a6");
findAndRemove(data, "599a12fdbf50847b0972a2ab");
console.log(data);
Cleared everything except middle list, just for better visualization.
#Abhijit Kar your one is working perfectly, thanks mate!
How I can later splice this list?
When I was working with objects from first array, I did it like this :
var inventory = jsonArrayList;
for (var i = 0; i < inventory.length; i++) {
if (inventory[i]._id == deleteProductById) {
vm.items.splice(i, 1);
break;
}
}
It would be very helpful, thanks alot!
You can use Array.map and Array.filter to accomplish this. Detailed explanation in comments:
PS: This snippet uses ES6 arrow functions and spread operator
function removeById(arr, id) {
// Array.map iterates over each item in the array,
// and executes the given function on the item.
// It returns an array of all the items returned by the function.
return arr.map(obj => {
// Return the same object, if the list is empty / null / undefined
if (!obj.list || !obj.list.length) return obj;
// Get a new list, skipping the item with the spedified id
const newList = obj.list.filter(val => val._id !== id);
// map function returns the new object with the filtered list
return { ...obj, list: newList };
});
}
const oldArray = <YOUR_ORIGINAL_ARRAY>;
const newArray = removeById(arr, "599a12fdbf50847b0972a2a5");

Checking a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }

jQuery UI Autocomplete - accessing nested objects in JSON

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/

Categories