Unable to loop through my postman response - arrays

I have this json respone from postman
I want to write a test to return failure if key "value" in the array is < 50.
It would loop through the array once the condition is not met it fails
I have tried this
pm.test('Matches value', () => {
_.each(pm.response.json(), (arrItem) => {
if (arrItem.persID === 'personID_2') {
throw new Error(`Array contains ${arrItem.persID}`)
}
})
});
My response
{
"groups": [
{
"title": "Maids",
"subTitle": null,
"description": null,
"featured": false,
"items": [
{
"id": "1",
"title": "AA",
"subTitle": "AA",
"thumbnail": "AA",
"priceStartingAt": {
"value": 50,
"baseCurrency": "USD",
"exchangeEnabled": true,
"exchangeRates": {
"aed": 3.672973
}
},
"categories": [
"Activity"
]
},
{
"id": "2",
"title": "BB",
"subTitle": "BB",
"thumbnail": "BB",
"priceStartingAt": {
"value": 20.01,
"baseCurrency": "USD",
"exchangeEnabled": true,
"exchangeRates": {
"aed": 3.672973
}
},
"categories": [
"Activity"
]
}
]
}
]
In this case the test should fail because the value in the second array is 20.01

I'm not sure where you copied that code from but it was never going to work as all the references relate to a different response body.
To keep the same convention and have the throw new Error in there you could do this:
pm.test('Value is not below 50', () => {
_.each(pm.response.json().groups[0].items, (arrItem) => {
if (arrItem.priceStartingAt.value < 50) {
throw new Error(`Array contains ${arrItem.priceStartingAt.value}`)
}
})
});
Or you could just check if the items are not below 50 like this.
pm.test('Value is not below 50', () => {
_.each(pm.response.json().groups[0].items, (arrItem) => {
pm.expect(arrItem.priceStartingAt.value).to.not.be.below(50)
})
});

Related

How to parse complex data using react native?

Following is the DATA that needs to parse which can nested arrays and objects i need
help understanding the easiest way to parse this .
const country= [
{
"place": "sikkim",
"location": 2,
"Extension": "",
"Keys": {
"string": [
"Enabled",
"Disabled"
]
},
"ItemValues": {
"ItemData": [
{
"Name": "Enabled",
"Data": {
"Rows": {
"Row": {
"Values": {
"Type": false
}
}
}
}
},
{
"Name": "Value",
"Data": {
"Rows": {
"DataRow": {
"Values": {
"anyType": "100"
}
}
}
}
}
]
}
},
{
"place": "assam",
"location": 1,
"Extension": "",
"Keys": {
"string": "MinValue"
},
"ItemValues": {
"ItemData": {
"Name": "nValue",
"Data": {
"Rows": {
"DataRow": {
"Values": {
"anyType": "1"
}
}
}
}
}
}
}
]
In this array 2 objects are there i need to parse this complex array of object and
show like this -
OUTCOME should be -
sikkim:{
"place": "sikkim",
"location": 2,
"Extension": "",
"string":"Enabled","Disabled",
"Name": "Enabled",
"Type": false,
"Name": "Value",
"anyType": 100
},
assam:{.. so on}
code that i tried is displaying only keys -
const getValues = country =>
country === Object(country)
? Object.values(country).flatMap(getValues)
: [country];
console.log(getValues(country));
OUTPUT from above code =
 ["sikkim", 2, "", "Enabled", "Disabled", "Enabled", false, "Value", "100",
"assam", 1, "", "MinValue", "nValue", "1"]
Need to write logic which is smart way to write to cover this logic because my data
is huge any leads?I can achieve the output but writing many for and if loops but that
creates lot of confusion.

How to delete objects from array

I want to remove object from array if they dont have a value
i have the API A, that returns to me this JSON:
{
"code": 0,
"data": [
{
"name": {
"value": "Ana"
},
"fruit": {
"value": "Grape"
},
"from": {
"value": "BR"
}
},
{
"name": {
"value": "Michael"
},
"fruit": {
"value": "Apple"
},
"from": {
"value": "US"
}
}
]
}
and with the API B, i can return the id for this user passing her the name
i have this code:
getData() {
this.myService.getDataAPI_A()
.subscribe((res) => {
this.myList = res['data'];
if (this.myList) {
for (const key of this.myList) {
this.getId(key.name.value);
}
}
});
}
getId(name) {
this.myService.getDataAPI_B(name) // api B returns id with the name
.subscribe((res) => {
this.myList.map((tempList) => {
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
return tempList;
}
return tempList;
});
});
}
then i got this json:
{
"code": 0,
"custodyBovespa": [
{
"name": {
"value": "Ana"
},
"userId": "43",
"fruit": {
"value": "Grape"
},
"from": {
"value": "BR"
}
},
{
"name": {
"value": "Michael"
},
"fruit": {
"value": "Apple"
},
"from": {
"value": "US"
}
}
]
}
Michael does not existe in my data base, so the api returns to me null,
and for some reason dont create the key in my json (why?).
after this i want to remove the object that dont have userId
how i can do this?
If you'd like your resultant array to contain only objects that contain the property userId, you can simply use plain JavaScript .filter.
In my below example, I am removing any element that does not have a "userId" prop.
var data = [
{
"name": {
"value": "Ana"
},
"userId": "43",
"fruit": {
"value": "Grape"
},
"from": {
"value": "BR"
}
},
{
"name": {
"value": "Michael"
},
"fruit": {
"value": "Apple"
},
"from": {
"value": "US"
}
}
];
var dataFiltered = data.filter(val => val["userId"]);
console.log(dataFiltered);
As you said:
Michael does not existe in my data base
and the condition you set is
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
return tempList;
}
return tempList;
As the your database doesn't have the the value 'Michael', The above condition is false. So, it gets out of the if clause and just return what it is without userId.
Now if you want to set the 'Michael' userId to null.
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
} else {
tempList.userId = null;
}
return tempList;
Then filter out the data's using like #Rich answered.
console.log(data.filter(val => val['userId'] !== null);

How to filter JSON object array across nested array with in it

I have an object array and i am filtering it against property name "username" like this.
array = [{
"id": 1,
"username": "admin",
"roles": [{
"name": "Administrator"
},
{
"name": "agent"
}
]
},
{
"id": 2,
"username": "admin2",
"roles": [{
"name": "Administrator2"
},
{
"name": "agent2"
}
]
},
{
"id": 3,
"username": "admin3",
"roles": [{
"name": "Administrator3"
},
{
"name": "agent3"
}
]
}
]
and the filter function is like this
transform(array: any, valueToSearch: string): any[] {
return array.filter(e =>
e.username.toLowerCase().indexOf(valueToSearch.toLowerCase())
!== -1);
}
everything works fine, but now i want to filter against the property name "name" in "roles" array in the object. for example i would like to return an object whose "roles" array contains "name" = agent3 , so it should return the whole object which is located at the last in my example. i tried like
return agents.filter(e => e.roles.filter(ee =>
ee.valueToSearch.toLowerCase()) !== -1));
but it didn't work.
this is dmeo
https://stackblitz.com/edit/angular-txchxs?embed=1&file=src/app/agentFilter.pipe.ts
As per the example given by you in the question, i was able to change your existing function like this and i hope this is your requirement..
ngOnInit() {
this.transform(this.array,'agent3');
}
transform(array: any, valueToSearch: string): any[] {
return this.array.filter(e => {
e.roles.filter(ee => {
if(ee.name.toLowerCase() === valueToSearch.toLowerCase() ) {
console.log(e);
this.finalResult = e;
}
})
})
}
Working Stackblitz: https://stackblitz.com/edit/angular-uzgni7
myarray = [{
"id": 1,
"username": "admin",
"roles": [{
"name": "Administrator"
},
{
"name": "agent"
}
]
},
{
"id": 2,
"username": "admin2",
"roles": [{
"name": "Administrator2"
},
{
"name": "agent2"
}
]
},
{
"id": 3,
"username": "admin3",
"roles": [{
"name": "Administrator3"
},
{
"name": "agent3"
}
]
}
];
function myFunction(){
var filtered= myarray.filter((obj)=>{
return obj.username.match(new RegExp(document.getElementById('search').value,'ig'));
});
console.log(filtered);
};
<input type="text" id="search" onkeyup="myFunction()"/>

DataTables - Load data from pre-defined JSON

I have a problem pointing dataTable to the right spot in the JSON. I receive a nested array:
{
"status": "ok",
"count": "7",
"msg ": "Operation Successful",
"data": [{
"contactHasServiceArea": true,
"issueCategories": [{
"id": "8",
"description": "Finance"
},
{
"id": "9",
"description": "Housing"
},
{
"id": "10",
"description": "International"
}
],
"cases": [{
"id": 31645,
"client_name": "Matthew",
"issue": "Assessment Completion",
"referral": null,
"opened_date": "10\/07\/2017",
"case_status": "Open"
}, {
"id": 31668,
"client_name": "Fanky ",
"issue": "Complex",
"referral": null,
"opened_date": "01\/07\/2017",
"case_status": "Open"
}]
}]
}
How do I point to the "cases" object? I'm sure this is simply, but I'm confused by the many options in the dataTables config.
I tried variations of data, dataSrc as well as data.cases or just cases, etc.
Thanks
$('#cases_table').DataTable( {
"ajax": "ajax/getCases",
"dataSrc" : "data.cases",
"data" : "cases",
"columns": [
{ "data": "client_name" },
{ "data": "issue" },
{ "data": "referral" },
{ "data": "opened_date" },
{ "data": "case_status" }
]
} );
You can configure like this:
$('#cases_table').DataTable( {
"ajax": {
"url": "ajax/getCases",
"dataSrc" : "data.cases"
},
"columns": [
{ "data": "client_name" },
{ "data": "issue" },
{ "data": "referral" },
{ "data": "opened_date" },
{ "data": "case_status" }
]
} );
datasrc points into the returns json. Remove the data option.

Insert array into sub-sub-document in mongoDB [duplicate]

I want add new data my nested array
My document is:
{
"username": "erkin",
"email": "erkin-07#hotmail.com",
"password": "b",
"playlists": [
{
"_id": 58,
"name": "asdsa",
"date": "09-01-15",
"musics": [
{
"name": "INNA - Cola Song (feat. J Balvin)",
"duration": "3.00"
},
{
"name": "blabla",
"duration": "3.00"
}
]
}
]
}
I want add music in this playlist section:
{
"username": "erkin",
"email": "erkin-07#hotmail.com",
"password": "b",
"playlists": [
{
"_id": 58,
"name": "asdsa",
"date": "09-01-15",
"musics": [
{
"name": "INNA - Cola Song (feat. J Balvin)",
"duration": "3.00"
},
{
"name": "blabla",
"duration": "3.00"
},
{
"name": "new",
"duration": "3.00"
}
]
}
]
}
Here is what I tried:
$users->update(
array(
'_id' => new MongoId (Session::get('id')),
'playlists._id' => $playlistId
),
array(
'$push' => array('playlists.musics' => array(
'name' => 'newrecord',
'duration' => '3.00'
))
)
);
Probably something like this where ID is your ObjectId. The first {} are necessary to identify your document. It is not required to use an ObjectId as long as you have another unique identifier in your collection.
db.collection.update(
{ "_id": ID, "playlists._id": "58"},
{ "$push":
{"playlists.$.musics":
{
"name": "test name",
"duration": "4.00"
}
}
}
)
This way it worked for me!
"playlists.$[].musics":
db.collection.update(
{ "_id": ID, "playlists._id": "58"},
{ "$push":
{"playlists.$[].musics":
{
"name": "test name",
"duration": "4.00"
}
}
}
)
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#position-nested-arrays-filtered
I suggest you using arrayFilters since it supports multiple nested documents and clearer.
db.collection.update(
{ "_id": ID},
{ "$push":
{"playlists.$[i].musics":
{
"name": "test name",
"duration": "4.00"
}
}
},
{
arrayFilters: [
{'i._id': 58,},
],
},
)
2022 update:
Full snippet:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/', maxPoolSize=50)
db = client.name_of_db
collection = db["name_of_collection"]
To push:
collection.find_one_and_update(
{"_id": 'id_of_the_document'},
{"$push": {"key":"value"}})
To push into nested:
collection.find_one_and_update(
{"_id": 'id_of_the_document'},
{"$push": {"key.nested_key":"value"}})

Resources