HTML form query JSON data for matches - javascript

I have to search through some JSON data looking for matches from an input form. Here is what I have so far:
<div class="container">
<form id="searchForm" class="form-group">
<input type="text" id="searchText" class="form-control />
</form>
</div>
Here's my JS ...
let searchForm = document.getElementById('searchForm');
searchForm.addEventListener('submit', function(e){
e.preventDefault();
let searchText = document.getElementById('searchText').value;
getCharacters(searchText);
});
function getCharacters(searchText){
let xhr = new XMLHttpRequest();
xhr.open('GET', 'characters.json', true);
xhr.onload = function(){
if(this.status == 200){
let characters = JSON.parse(this.responseText);
let output = '';
for(let i in characters){
output +=
...
;
}
document.getElementById('characters').innerHTML = output;
}
}xhr.onerror = function(){
console.log('Request error');
}xhr.send();
};
And my JSON ...
[
{
"id": 1001,
"first_name": "Rick",
"last_name": "Grimes",
"img": "https://ia.media-imdb.com/images/M/MV5BMjI2NDYyNjg4NF5BMl5BanBnXkFtZTcwMjI5OTMwNA##._V1_.jpg",
"career": "Sheriff",
"actor": "Andrew Lincoln",
"still_alive": true,
"tags": ["rick","grimes","sheriff","andrew","lincoln","alive"]
},
{
"id": 1002,
"first_name": "Daryl",
"last_name": "Dixon",
"img": "https://ia.media-imdb.com/images/M/MV5BMTQ5ODE4NTgzMl5BMl5BanBnXkFtZTcwODI0MjAwMw##._V1_.jpg",
"career": "unknown",
"actor": "Norman Reedus",
"still_alive": true,
"tags": ["daryl","dixon","unknown","norman","reedus","alive"]
},
{
"id": 1003,
"first_name": "Glenn",
"last_name": "Rhee",
"img": "https://ia.media-imdb.com/images/M/MV5BMTcxODE2MDgxOF5BMl5BanBnXkFtZTgwNjk2MDM1NzE#._V1_.jpg",
"career": "Nerd",
"actor": "Steven Yeun",
"still_alive": false,
"tags": ["glenn","rhee","nerd","steven","yeun","dead"]
}
]
Within the JS I am looking for a way to use the searchText to query the JSON based on either first_name, last_name or tags. From there I will output the matching data into a div for each match.
Need help with the query part! Everything else I have working but I'm stuck at this point. All help is greatly appreciated!

First parse it from JSON to JS object then filter it
let objectsFromXHR = JSON.parse(`[
{
"id": 1001,
"first_name": "Rick",
"last_name": "Grimes",
"img": "https://ia.media-imdb.com/images/M/MV5BMjI2NDYyNjg4NF5BMl5BanBnXkFtZTcwMjI5OTMwNA##._V1_.jpg",
"career": "Sheriff",
"actor": "Andrew Lincoln",
"still_alive": true,
"tags": ["rick","grimes","sheriff","andrew","lincoln","alive"]
},
{
"id": 1002,
"first_name": "Daryl",
"last_name": "Dixon",
"img": "https://ia.media-imdb.com/images/M/MV5BMTQ5ODE4NTgzMl5BMl5BanBnXkFtZTcwODI0MjAwMw##._V1_.jpg",
"career": "unknown",
"actor": "Norman Reedus",
"still_alive": true,
"tags": ["daryl","dixon","unknown","norman","reedus","alive"]
},
{
"id": 1003,
"first_name": "Glenn",
"last_name": "Rhee",
"img": "https://ia.media-imdb.com/images/M/MV5BMTcxODE2MDgxOF5BMl5BanBnXkFtZTgwNjk2MDM1NzE#._V1_.jpg",
"career": "Nerd",
"actor": "Steven Yeun",
"still_alive": false,
"tags": ["glenn","rhee","nerd","steven","yeun","dead"]
}
]`);
const target = 'Glenn'
console.log(objectsFromXHR.filter(each => each.first_name === target));
It filter function you can use Regex etc. Just return true to let JS know this currect filtering object is valid

To search by first and last name, you can combine 2 string and then cast it to lowercase, and then compare with your inputs.
I added an empty string at the end in case both fields are empty.
This method is case-insensitive and removes empty inputs in front and end.
const obj = [
{
"id": 1001,
"first_name": "Rick",
"last_name": "Grimes",
"img": "https://ia.media-imdb.com/images/M/MV5BMjI2NDYyNjg4NF5BMl5BanBnXkFtZTcwMjI5OTMwNA##._V1_.jpg",
"career": "Sheriff",
"actor": "Andrew Lincoln",
"still_alive": true,
"tags": ["rick","grimes","sheriff","andrew","lincoln","alive"]
},
{
"id": 1002,
"first_name": "Daryl",
"last_name": "Dixon",
"img": "https://ia.media-imdb.com/images/M/MV5BMTQ5ODE4NTgzMl5BMl5BanBnXkFtZTcwODI0MjAwMw##._V1_.jpg",
"career": "unknown",
"actor": "Norman Reedus",
"still_alive": true,
"tags": ["daryl","dixon","unknown","norman","reedus","alive"]
},
{
"id": 1003,
"first_name": "Glenn",
"last_name": "Rhee",
"img": "https://ia.media-imdb.com/images/M/MV5BMTcxODE2MDgxOF5BMl5BanBnXkFtZTgwNjk2MDM1NzE#._V1_.jpg",
"career": "Nerd",
"actor": "Steven Yeun",
"still_alive": false,
"tags": ["glenn","rhee","nerd","steven","yeun","dead"]
}
];
function searchByName(data, str) {
return data.filter(i => {
const pool = i.first_name + i.last_name + '';
return pool.toLowerCase().includes(str.trim().toLowerCase());
});
}
console.log(searchByName(obj, 'Rhe'));

Related

how to delete a element from the array of objects

Here i have got array of objects data, from this data i need to delete the element based on a value, if value is found then delete entire element
let value = "/unifiedconfig/config/agent/5197";
//if this found in json data i have delete complete element{"refURL":"/unifiedconfig/config/agent/5197","agentId":"1085","firstName":"Owen","lastName":"Harvey","userName":"oharvey"}
var myjsonobj = {
"refURL": "/unifiedconfig/config/agentteam/5022",
"changeStamp": 12,
"agentCount": 7,
"description": "Cumulus Outbound Team",
"name": "CumulusOutbound",
"peripheral": {
"id": 5000,
"name": "CUCM_PG_1"
},
"peripheralId": 5000,
"supervisorCount": 1,
"agents": [{
"agent": [{
"refURL": "/unifiedconfig/config/agent/5197",
"agentId": "1085",
"firstName": "Owen",
"lastName": "Harvey",
"userName": "oharvey"
}, {
"refURL": "/unifiedconfig/config/agent/5201",
"agentId": "1320",
"firstName": "Bruce",
"lastName": "Wayne",
"userName": "bwayne"
}, {
"refURL": "/unifiedconfig/config/agent/5202",
"agentId": "1321",
"firstName": "Peter",
"lastName": "Parker",
"userName": "pparker"
}, {
"refURL": "/unifiedconfig/config/agent/5203",
"agentId": "1322",
"firstName": "Tony",
"lastName": "Stark",
"userName": "tstark"
}, {
"refURL": "/unifiedconfig/config/agent/5204",
"agentId": "1323",
"firstName": "Steve",
"lastName": "Rogers",
"userName": "srogers"
}, {
"refURL": "/unifiedconfig/config/agent/5205",
"agentId": "1324",
"firstName": "Bruce",
"lastName": "Banner",
"userName": "bbanner"
}, {
"refURL": "/unifiedconfig/config/agent/5231",
"agentId": "1086",
"firstName": "Annika",
"lastName": "Hamilton",
"userName": "annika"
}, {
"refURL": "/unifiedconfig/config/agent/5118",
"agentId": "1317",
"firstName": "Donald",
"lastName": "Duckling",
"userName": "dduck"
}]
}],
"supervisors": [{
"supervisor": [{
"refURL": "/unifiedconfig/config/agent/5174",
"agentId": "1082",
"firstName": "Rick",
"lastName": "Barrows",
"userName": "rbarrows#dcloud.cisco.com"
}]
}]
}
Object.keys(myjsonobj).forEach(function(key) {
if (myjsonobj[key] === value) {
delete myjsonobj[key];
}
});
console.log(JSON.stringify(myjsonobj));
This should do the trick:
var myjsonobj = {"refURL": "/unifiedconfig/config/agentteam/5022","changeStamp": 12,"agentCount": 7,"description": "Cumulus Outbound Team","name": "CumulusOutbound","peripheral": {"id": 5000,"name": "CUCM_PG_1"},"peripheralId": 5000,"supervisorCount": 1,"agents": [{"agent": [{"refURL": "/unifiedconfig/config/agent/5197","agentId": "1085","firstName": "Owen","lastName": "Harvey","userName": "oharvey"}, {"refURL": "/unifiedconfig/config/agent/5201","agentId": "1320","firstName": "Bruce","lastName": "Wayne","userName": "bwayne"}, {"refURL": "/unifiedconfig/config/agent/5202","agentId": "1321","firstName": "Peter","lastName": "Parker","userName": "pparker"}, {"refURL": "/unifiedconfig/config/agent/5203","agentId": "1322","firstName": "Tony","lastName": "Stark","userName": "tstark"}, {"refURL": "/unifiedconfig/config/agent/5204","agentId": "1323","firstName": "Steve","lastName": "Rogers","userName": "srogers"}, {"refURL": "/unifiedconfig/config/agent/5205","agentId": "1324","firstName": "Bruce","lastName": "Banner","userName": "bbanner"}, {"refURL": "/unifiedconfig/config/agent/5231","agentId": "1086","firstName": "Annika","lastName": "Hamilton","userName": "annika"}, {"refURL": "/unifiedconfig/config/agent/5118","agentId": "1317","firstName": "Donald","lastName": "Duckling","userName": "dduck"}]}],"supervisors": [{"supervisor": [{"refURL": "/unifiedconfig/config/agent/5174","agentId": "1082","firstName": "Rick","lastName": "Barrows","userName": "rbarrows#dcloud.cisco.com"}]}]}
let value = "/unifiedconfig/config/agent/5197";
myjsonobj.agents[0].agent=myjsonobj.agents[0].agent.filter(a=>a.refURL!=value);
console.log(myjsonobj)
From your data it looks pretty obvious that the target value can only be found in the refURL property of the agent-elements. So this is what I focused on in the above script.

Postman - Looping through an array of nested objects to make a variable

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 !?

How to verify in postman regardless of the number of results if the result returns

How to verify in postman regardless of the number of results that all of data in the response returns id, firstname, lastname etc
Here is what response look like:
[
{
"id": 1,
"first_name": "Sebastian",
"last_name": "Eschweiler",
"email": "sebastian#codingthesmartway.com"
},
{
"first_name": "Sebastian",
"last_name": "Eschweiler",
"email": "sebastian#codingthesmartway.com",
"id": 4
},
{
"id": 5,
"first_name": "Sebastian",
"last_name": "Eschweiler",
"email": "sebastian#codingthesmartway.com"
},
{
"first_name": "Sebastian",
"last_name": "Eschweiler",
"email": "sebastian#codingthesmartway.com",
"id": 8
},
{
"id": 9,
"first_name": "Sebastian",
"last_name": "Eschweiler",
"email": "sebastian#codingthesmartway.com"
},
{
"first_name": "Sebastian",
"last_name": "Eschweiler",
"email": "sebastian#codingthesmartway.com",
"id": 12
}
]
I want to verify two things:
1) The response returns id, first_name, last_name, email
2) All the first_name is equal to "Sebastian" regardless there is only one result or 100
This is what i tried however, it only works for one result:
const jsonData = pm.response.json();
pm.test('Has data', function() {
pm.expect(jsonData).to.have.property('first_name');
pm.expect(jsonData).to.have.property('last_name');
pm.expect(jsonData).to.have.property('email');
pm.expect(jsonData).to.have.property('id');
});
You could try this:
pm.test("Has data",() => {
_.each(pm.response.json(), (item) => {
pm.expect(item.first_name).to.eql("Sebastian")
pm.expect(item).to.have.property('first_name')
pm.expect(item).to.have.property('last_name')
pm.expect(item).to.have.property('email')
pm.expect(item).to.have.property('id')
})
})
This will work based on the data set you provided.

JSON.PARSE without loosing header array field

function main(message){
...
phone= JSON.parse(message.phoneNumbers);
... }
My input JSON is
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
The result I receive is omitting the "phoneNumbers" but I do want it.
Your data is correct, when i JSON.parse it, i get everything allright.
But you don't seem to access to your data in the right way. You must first parse the whole JSON, then you have a javascript object, and only then you can acces your property.
in detail:
var obj = JSON.parse(message);
var phone = obj.phoneNumbers;
or in short:
var phone = (JSON.parse(message)).phoneNumbers;

JavaScript - Loop JSON array and match string in subarray

I have JSON array with subarrays and I want to loop it and find if username of user is for example 'admin'. If so then create JSON array contains data belonging to user 'admin' (region, sport, city etc). I don't have idea how to find it in loop and then slice it. I'm sorry for stupid question but I'm a little lost.
This is JSON array with structure what I have:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
]
Edit:
the expected result of user 'admin' is then:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
}]
Loop through the array and pull out each item with a user with a username of admin:
var result = [];
var nameToSearchFor = 'admin';
for(var index = 0; index < arr.length; index++)
{
var item = arr[index];
if(item.user.username === nameToSearchFor)
{
result.push(item);
}
}
One solution to your problem is to search for the index that resides the admin username. In your case is at the 0 index of the json array provided. So you can get the entire object by the index, like this:
var i = 0;
for(; i< json.length; i++){
if(json[i].user.username === "admin") break;
}
With that now you can get the object with the admin data. Like this:
json[i].user.firstName
Check this plunk here
EDIT
If you want just to get that slice to a new array perhaps then you can just slice that piece of the json array, now that you have the index.
var newArray = json.slice(i, i+1);
You can use an open source project like jinqJs to perform SQL like queries on arrays.
var data = [
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
];
var result = jinqJs()
.from(data)
.where(function(row){return row.user.username==='admin';})
.select();
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>

Categories