get index of dictionary from array of dictionary in swift? - arrays

How to get a specific dictionary from array of dictionary by giving key alone in method.
we studied about indexOf method in array but we are not sure about how to pass key and get a index of particular key.
Here is Array of dictionary
[
{
"Twitter0":"NSLayoutConstraint"
},
{
"Twitter1":"NSLayoutConstraint"
},
{
"Insta2":"NSLayoutConstraint"
},
{
"Twitter3":"NSLayoutConstraint"
},
{
"Insta4":"NSLayoutConstraint"
}
]
I just want to pass key name like Twitter2 in method.
We tried this Link, we dont know how to process with key
Thanks in advance..

You can use firstIndex(where:) and pass a closure to it:
arrayOfDicts.firstIndex(where: { $0.keys.contains("Twitter2")})
Or more generally with key:
arrayOfDicts.firstIndex(where: { $0.keys.contains(key)})

Related

Mongo find position by id in an Array of Objects

I have a range of documents
{
_id: ObjectId("5e388da4df54cb8efb47e61b"),
userId:'test_user'
productId:'product_6_id'
recommendations:{
_id:123
rankedList:[
0:{id:ObjectId('product_5_id'),Name:'Product_5'},
1:{id:ObjectId('product_6_id'),Name:'Product_6'},
2:{id:ObjectId('product_3_id'),Name:'Product_3'}],
Date:'2020-02-25T05:03:55.439+00:00'
}
},
{
_id: ObjectId("5e388da4df54cb8efb47e62b"),
userId:'test_user1'
productId:'product_3_id'
recommendations:{
_id:123
rankedList:[
0:{id:ObjectId('product_1_id'),Name:'Product_1'},
1:{id:ObjectId('product_5_id'),Name:'Product_5'},
2:{id:ObjectId('product_3_id'),Name:'Product_3'}],
Date:'2020-02-25T05:03:55.439+00:00'
}
}
and I need to find each time the position of productId within the Array of objects rankedList.
Thus here the answer would be positionIndex=1 for first doc and positionIndex=2 for second document.
I am quite confused with $indexOfArray and how I should use it here with aggregate.
Yes, you need $indexOfArray. The tricky part is that recommendations.rankedList is an array of objects however MongoDB allows you to use following expression:
$recommendations.rankedList.id
which evaluates to a list of strings, ['product_5_id', 'product_6_id', 'product_3_id'] in this case so your code can look like this:
db.collection.aggregate([
{
$project: {
index: {
$indexOfArray: [ "$recommendations.rankedList.id", "$productId" ]
}
}
}
])
Mongo Playground

Iterate array containing custom index

I am doing a small project in Angular8 and i have an array which contains data of users as object. This array is provided to me by the client which i can not change.
[
{
id:045#71,
name:'Ahmad',
isActive: false
},
{
id:047#71,
name:'John',
isActive: false
},
{
id:048#71,
name:'Doe',
isActive: false
}
]
In this array i have id's as custom indexes because of which i am not able to iterate this array. I am getting undefined in console when i try to iterate the array . Is there a way to iterate array with custom indexes. I even tried forEach loop but it is not working as well.
The method i used:
usersArray = [
{
id:045#71,
name:'Ahmad',
isActive: false
},
{
id:047#71,
name:'John',
isActive: false
},
{
id:048#71,
name:'Doe',
isActive: false
}
];
ngOnInit() {
this.usersArray.forEach((user)=>{
console.log(user.id + ' - ' + user.name);
})
}
What you have is what we typically call a collection. You can access an item from the collection if you know its index. In most cases, the index is an integer greater or equal to zero. i.e. collection[0] will give you the first item.
You can use collection.find(el => el.id ==='045#71') to find an element in the collection, if it doesn't exist will return undefined.
To find the index of an item you can use collection.findIndex(el => el.id ==='045#71'), in this case it will return 0
If you want to use customer indexes you would have to convert the collection into an object that uses your custom indexes as keys. There's surprisingly also a way to use custom keys in an array but it's not common practice in JavaScript.

MongoDB Update a value from Object in Array in Object in Array

i want to update the value. The gap should be located with his id and the id from the pocket.
I tried with the updateOne() function but i could not find the path vor the gap.
Maybe you can help me.
There will be more objects in the pockets and gaps arrays.
{
"_id":"5a4f535f4dc4b200d43cf333",
"id":"A07","name":"name",
"capacity":"230",
"free":"230",
"open":false,
"location":
{
"longitude":51.02274,
"latitude":7.5612
},
"pockets":
[
{
"id":"A",
"description":"Parktasche",
"capacity":12,
"free":11,
"gaps":
[
{
"id":"7",
"value":true, <-- should be updating
"deployee":false,
"disabled":false,
"guest":false,
"pid":"A"
}
]
}
]
}
If I remember correctly, you need something like pockets.$.gaps.$.value
https://docs.mongodb.com/manual/reference/operator/update/positional/#update-documents-in-an-array

Angular2 avoid adding duplicate JSON objects to array

I'm trying to avoid adding duplicate objects to an Angular2 array. For example let's say we have an array "Cars" and we put in a JSON object in that array that might be something like:
{
"brand": "Acura"
"engine": "2.4L"
+ others details
}
We can keep adding cars with to the array. My issue is now how to avoid adding the same car into the array again. If I were to add the same JSON as described above, it shouldn't be added. Would I have to iterate through all the existing objects in the array and compare each field of the JSON? This sounds like an expensive operation to me, or is there some more elegant/faster method?
Thanks!
If each car has something unique about it (like an ID), you could use an object instead of an array:
var map = { };
function add(car) {
if (map[car.id]) {
return;
}
map[car.id] = car;
}
Your ID could be something else unique, like a combination of the brand and year or something similar.
map[car.brand + car.year] = car
You need to find or create a unique property on the items in the list, then you could use something like lodash to query the array by a property to see if that item already exists in the list before you add it.
Example from Lodash site
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });

MongoDB push data to specific array element

Hi guys so I'm doing meteor mongo db, I use findAndModify package
Ips.findAndModify({
//Find the desired document based on specified criteria
query: {
"ipAdr": clientIp,
connections: {
$elemMatch: {
connID: clientConnId
}
}
},
//Update only the elements of the array where the specified criteria matches
update: {
$push: {
'connections': {
vid: result.data.vid,
firstName: result.data.properties.firstname.value,
lastName: result.data.properties.lastname.value
}
}
}); //Ips.findAndModify
So I find the element that I need however my info is being pushed to the whole connections array, but I want to push my info into that specific element. What should I do here? I tried
$push: {
'connections.$': {
vid: result.data.vid,
but it gives error.
Please help.
You don't need to use the $push operator here as it adds a new element to array, instead you need to modify an element that is already in the array, try the $set operator to update as follows:
update: {
$set: {
'connections.$.vid': result.data.vid,
'connections.$.firstName': result.data.properties.firstname.value,
'connections.$.lastName': result.data.properties.lastname.value
}
}
Take into account that this way you will change only one element of the array that satisfies the condition from the $elemMatch statement.

Resources