Javascript For Each Object inside Array containing a property that is Array check If Value Matches - javascript

For each object inside this array containing userHandle array loop through that array(userHandle one) and check if one of those values matches some string I choose called uid. How to write that code in Javascript?
Array [
Object {
"avatar": null,
"hugCount": 2,
"id": 35,
"liked": false,
"name": "fhfdhdhf",
"text": "Yoho",
"timestamp": 1610471860157,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
},
Object {
"avatar": null,
"hugCount": 1,
"id": 34,
"liked": true,
"mood": 2,
"name": "fhfdhdhf",
"text": "I'm fine today.",
"timestamp": 1607943705709,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
"userHandle": Array [
"Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
"LrIwIx9I1xQBJ7aeCSrinpEaDP53",
],
}]

Try this code:
var uid = "LrIwIx9I1xQBJ7aeCSrinpEaDP53";
yourArray.forEach(function(item, _){
return item['userHandle']?.indexOf(uid);
});
The '?' is to make sure your Object contains the 'userHandle' property

This is the function you need... and below you can see how to use it.
You need to pass the value you are looking for, and the array with the information.
function findInUserHandle(uidValue, array)
{
return array.reduce
(
(acum, current) =>
current.userHandle && current.userHandle.indexOf(uidValue) !== -1 || acum,
false
)
}
let array = [
{
"avatar": null,
"hugCount": 2,
"id": 35,
"liked": false,
"name": "fhfdhdhf",
"text": "Yoho",
"timestamp": 1610471860157,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
},
{
"avatar": null,
"hugCount": 1,
"id": 34,
"liked": true,
"mood": 2,
"name": "fhfdhdhf",
"text": "I'm fine today.",
"timestamp": 1607943705709,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
"userHandle":[
"Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
"LrIwIx9I1xQBJ7aeCSrinpEaDP53",
],
}
]
findInUserHandle('something', array) //? false
findInUserHandle('Aw8AUj1mPkON1Fd1s6LhkNETHfb2', array) //? true
findInUserHandle('mood', array) //? false

Related

Laravel Sorted Collection Gets Undone When Passed to Javascript [duplicate]

Here is my code :
public function list()
{
$users = User::with('group')->get()->toArray();
return response()->json([
'clients' => array_filter($users, function ($r) {
return $r['group']['name'] === 'client';
}),
'employes' => array(array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
})),
]);
}
Here is the response :
{
"clients": {
"2": {
"id": 3,
"name": "Client 1",
"email": "client#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
"3": {
"id": 4,
"name": "Client 2",
"email": "client2#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
"4": {
"id": 5,
"name": "Client 3",
"email": "client3#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
}
},
"employes": [
[
{
"id": 1,
"name": "Alexis",
"email": "alexis#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 1,
"group": {
"id": 1,
"name": "admin"
}
},
{
"id": 2,
"name": "guest",
"email": "guest#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 2,
"group": {
"id": 2,
"name": "guest"
}
}
]
]
}
I tried to change the conditions of the array_filter. Sometimes I have an array, sometimes I have an object. I don't understand how this is determined
Stackoverflow tells me "It looks like your post is mostly code; please add some more details." So ... what details to add?
Thank you
Internally array_filter() filters matching entries from the array, and returns them with their indices intact. This is very important, as it is the core reason you're getting an object and not an array in JavaScript.
In PHP, this is fine; arrays can start at 0, or another index, such as 2, and function as an array without issue. This is due to the existence of indexed (0-based) and associative (numeric/non-numeric key based) arrays.
In JavaScript, arrays cannot be "associative", i.e. they must start at 0. object classes on the other hand function similarly to associative arrays, but the key difference is that they aren't explicitly arrays.
Now that you know the why, the next question is "how do I fix this?" The simple method is to wrap array_filter() with a function that simply returns the values of the new array. This inherently will "re-index" the array with 0-based values, which when converted to JSON will result in correct arrays being returned:
$users = User::with('group')->get()->toArray();
$clients = array_filter($users, function($r){
return $r['group']['name'] === 'client';
});
$groups = array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
});
return response()->json([
'clients' => array_values($clients),
'groups' => array_values($groups)
]);
As a sidenote, Collection classes have similar logic, and I prefer to use Laravel's Collection class whenever possible:
$users = User::with('group')->get();
$clients = $users->filter(function($r){
$r->group->name === 'client';
});
$groups = $users->filter(function($r){
$r->group->name !== 'client';
});
return response()->json([
'clients' => $clients->values(),
'groups' => $groups->values()
]);
But again, that's my preference; either approach should work, so use what you're used to.
References:
PHP Array Methods:
https://www.php.net/manual/en/function.array-filter.php
https://www.php.net/manual/en/function.array-values.php
Laravel Collection Methods:
https://laravel.com/docs/5.8/collections#method-filter
https://laravel.com/docs/5.8/collections#method-values
This works for me. I hope this will help anyone.
return response(['STATUS'=>'true','message'=>'Your Message','response'=>
array_values('clients' => array_filter($users, function ($r) {
return $r['group']['name'] === 'client';
})),
'employes' => array_values(array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
}))
)]);
If in response array you will get a result like an index key and you want the response in object array [{ ... }] then use array_values() will resolve your problem.
"clients": {
"2": {
"id": 3,
"name": "Client 1",
"email": "client#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
simply add ->values() it will reorder array keys
users = User::with('group')->values();

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

React-Native remove object from Array

I'm trying to remove an object from the array, even though, I'm not sure how to grab the object, which basically makes the code that is written not make anything.
Let me show the existing array:
Object {
"created_at": "2020-06-30T11:22:53.000000Z",
"icon": "subjectImgs/509-1080x1080.jpg",
"id": 2,
"name": "Test",
"updated_at": "2020-06-30T11:22:53.000000Z",
"user_id": 1,
},
Object {
"created_at": "2020-06-04T18:32:25.000000Z",
"icon": "subjectImgs/698-1080x1080.jpg",
"id": 1,
"name": "history",
"updated_at": "2020-06-04T18:32:25.000000Z",
"user_id": 1,
},
Object {
"created_at": "2020-07-08T16:32:03.000000Z",
"icon": "subjectImgs/698-1080x1080.jpg",
"id": 21, // Here is the ID
"name": "123",
"updated_at": "2020-07-08T16:32:03.000000Z",
"user_id": 1,
},
}
When the event is listened to, I get the array of the object that was just deleted:
Object {
"socket": null,
"subject": Object {
"created_at": "2020-07-08T16:32:03.000000Z",
"icon": "subjectImgs/698-1080x1080.jpg",
"id": 21, // Here is the ID
"name": "123",
"updated_at": "2020-07-08T16:32:03.000000Z",
"user_id": 1,
},
}
Now, the way I'm trying to delete it is the following:
.listen('SubjectRemoved', ev => {
var array = this.state.subjects
this.setState({ subjects: array.filter((id) => id != ev.subject.id) })
});
but apparently, this is not working. I assume because of using id really gets nothing.
I think that the problem is in the filter method:
array.filter((id) => id != ev.subject.id) // here id is an elemt of the array not the real id
You could try
array.filter((subject) => subject.id != ev.subject.id) //if is an array of subjects
or
array.filter((elem) => elem.subject.id != ev.subject.id) //if is an array of objects like {socket: null, subject: {... with the fields }}
If you think that the ev.subject.id is not working you could just console.log it before the filter senetence.

Laravel - why json response return sometimes an array sometimes an object

Here is my code :
public function list()
{
$users = User::with('group')->get()->toArray();
return response()->json([
'clients' => array_filter($users, function ($r) {
return $r['group']['name'] === 'client';
}),
'employes' => array(array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
})),
]);
}
Here is the response :
{
"clients": {
"2": {
"id": 3,
"name": "Client 1",
"email": "client#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
"3": {
"id": 4,
"name": "Client 2",
"email": "client2#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
"4": {
"id": 5,
"name": "Client 3",
"email": "client3#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
}
},
"employes": [
[
{
"id": 1,
"name": "Alexis",
"email": "alexis#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 1,
"group": {
"id": 1,
"name": "admin"
}
},
{
"id": 2,
"name": "guest",
"email": "guest#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 2,
"group": {
"id": 2,
"name": "guest"
}
}
]
]
}
I tried to change the conditions of the array_filter. Sometimes I have an array, sometimes I have an object. I don't understand how this is determined
Stackoverflow tells me "It looks like your post is mostly code; please add some more details." So ... what details to add?
Thank you
Internally array_filter() filters matching entries from the array, and returns them with their indices intact. This is very important, as it is the core reason you're getting an object and not an array in JavaScript.
In PHP, this is fine; arrays can start at 0, or another index, such as 2, and function as an array without issue. This is due to the existence of indexed (0-based) and associative (numeric/non-numeric key based) arrays.
In JavaScript, arrays cannot be "associative", i.e. they must start at 0. object classes on the other hand function similarly to associative arrays, but the key difference is that they aren't explicitly arrays.
Now that you know the why, the next question is "how do I fix this?" The simple method is to wrap array_filter() with a function that simply returns the values of the new array. This inherently will "re-index" the array with 0-based values, which when converted to JSON will result in correct arrays being returned:
$users = User::with('group')->get()->toArray();
$clients = array_filter($users, function($r){
return $r['group']['name'] === 'client';
});
$groups = array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
});
return response()->json([
'clients' => array_values($clients),
'groups' => array_values($groups)
]);
As a sidenote, Collection classes have similar logic, and I prefer to use Laravel's Collection class whenever possible:
$users = User::with('group')->get();
$clients = $users->filter(function($r){
$r->group->name === 'client';
});
$groups = $users->filter(function($r){
$r->group->name !== 'client';
});
return response()->json([
'clients' => $clients->values(),
'groups' => $groups->values()
]);
But again, that's my preference; either approach should work, so use what you're used to.
References:
PHP Array Methods:
https://www.php.net/manual/en/function.array-filter.php
https://www.php.net/manual/en/function.array-values.php
Laravel Collection Methods:
https://laravel.com/docs/5.8/collections#method-filter
https://laravel.com/docs/5.8/collections#method-values
This works for me. I hope this will help anyone.
return response(['STATUS'=>'true','message'=>'Your Message','response'=>
array_values('clients' => array_filter($users, function ($r) {
return $r['group']['name'] === 'client';
})),
'employes' => array_values(array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
}))
)]);
If in response array you will get a result like an index key and you want the response in object array [{ ... }] then use array_values() will resolve your problem.
"clients": {
"2": {
"id": 3,
"name": "Client 1",
"email": "client#a.fr",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
simply add ->values() it will reorder array keys
users = User::with('group')->values();

Remove object from array if nested object has certain value

I am trying to return an array from a json object.
Each object has some data and another nested array/object
like this:
{
"data": [
{
"name": "name",
"id": "id",
"amount": 4000,
"items": [
{
"number": 12,
"isAvailable": true,
},
{
"number": 15,
"isAvailable": true,
},
{
"number": 16,
"isAvailable": true,
},
{
"number": 17,
"isAvailable": true,
}
]
},
{
"name": "name2",
"id": "id2",
"amount": 3000,
"items": [
{
"number": 12,
"isAvailable": true,
},
{
"number": 15,
"isAvailable": true,
},
{
"number": 16,
"isAvailable": false,
},
{
"number": 17,
"isAvailable": true,
}
]
},
{
"name": "name4",
"id": "id4",
"amount": 1200,
"items": [
{
"number": 12,
"isAvailable": true,
},
{
"number": 15,
"isAvailable": true,
},
{
"number": 16,
"isAvailable": true,
},
{
"number": 17,
"isAvailable": true,
}
]
}
]
}
I want to check all objects and see if in any of these objects has a item that has "isAvailable": false
If an item is not available I need to remove the parent object from the array (so not the item array but the full object above that.
Then I would like to return the array where this object has been removed.
I got this to work by using ES6 findIndex
array.findIndex(object => object.items.some(item => !item.isAvailable));
Which will return the index of the parent array that has it, which I can use to splice the array. But this only works on a single object. If I have another object it will still return the first index.
How can I check if multiple objects exist based on the criteria and remove them from an array?
You might use .filter instead of .findIndex and then reassign the array to the new filtered array:
const removed = data.filter(object => object.items.some(item => !item.isAvailable));
data = data.filter(item => !removed.includes(item));
If you need to mutate and not just reassign, you might splice while filtering:
const removed = data.filter(object => {
const toRemove = object.items.some(item => !item.isAvailable);
if (!toRemove) return false;
// Have to use `indexOf` rather than the second filter argument
// because the index of the object might change due to an earlier splice:
data.splice(data.indexOf(object), 1);
return true;
});

Categories