How to add json array to object in existing array? - arrays

I have an object myObj.employees which looks like this:
{"employees":[{"key":1419,"rankid":8,"label":"bob (47)","exclude":false,"color":"#ffffff","textColor":"#330000","active_events":[]},{"key":1420,"rankid":8,"label":"john (48)","exclude":false,"color":"#ffffff","textColor":"#330000","active_events":[]}]}
how do I add items to active_events for key = 1419 ?

Find the 1419 entry:
const entry = myObj.employees.find(obj => obj.key === 1419);
Add entries to active events:
entry.active_events.push("more item");

If you're working in Javascript you can use the .forEach function to iterate over the employees array in a brute force manner.
myObj.employees.forEach(function(e) {
if (e.key === 1419) {
e.active_events.push("waffles")
}
});

myObj.employees["employees"][0]["active_events"].append("new event")
unless the object you showed was really just myObj in which case the answer (in python) would be:
myObj["employees"][0]["active_events"].append("new event")
let's break this down.
We take your object (myObj.employees) which gives us a dictionary with one key value pair.
We dive into ["employees"] to access the employee list.
You want to edit the [0] index employee
You want to edit the ["active_events"] value
You want to append / edit the list. I think you can take it from here.
As others have show if you do not know the index of the employee you want to edit, which you probably won't, then you'll need to loop through and look for it.
for i, employee in enumerate(myObj["employees"]):
if employee["key"] == 1419:
myObj["employees"][i]["active_events"].append('new event')

Related

How to remove a key in object in array

I have an address that looks like this
let address = [{"_id":"6013a6ef20f06428741cf53c","address01":"123","address02":"512","postcode":"23","state":"512","country":"32","key":1},{"_id":"6013a6eh6012428741cf53c","address01":"512","address02":"6","postcode":"6612","state":"33","country":"512","key":2}]
How can I remove '_id' and 'key' together with its Key and Value Pair.
And can you please let me know how does this type of array is called? Is it called Object in Array? I keep seeing this type of array but I have no clue how to deal with this, is there like a cheatsheet to deal with?
You can access the property of the object like this:
address[0]["_id"]
// or
address[0]._id
and you can delete the property like this:
delete address[0]["_id"]
// or
delete address[0]._id
Where 0 is the 1st index of the array. You might need to iterate over your array and remove the property from each object:
address.forEach(a => {
delete a._id;
delete a.key;
});
First, this type of array is called "Array of Objects" (objects inside array)
Second, you can generate new set of array by delete the key which you want to remove by,
let newSetOfArray = address.map((obj)=> {
delete obj._id;
delete obj.key;
return obj;
});
console.log(newSetOfArray); // this array of objects has keys with absence of _id & key.

Perform a task with all of the values in an array (Swift, Firebase)

My situation is that I am creating a social media app, and I have an array of all of the people that the user is following. It looks like this:
let followingArray:[String] = ["user1Uid", "user2Uid", "user3Uid", "user4Uid"]
So, I want to perform a function using every userUid in the array to fetch their posts and display it onto a collectionView.
To give more context the function looks like this (the "userUid" is the element that I need to repeat with all of the userUid's using the array):
databaseRef.child("posts").child(userUid).observeSingleEvent(of: .value) { (snapshot) in
// all of the code to get the posts information into another array to display on the collection view.
}
Thanks a lot!
To do something with every element in an array you can always use forEach(_:). Try:
let followingArray:[String] = ["user1Uid", "user2Uid", "user3Uid", "user4Uid"]
for userID in followingArray {
databaseRef.child("posts").child(userID).observeSingleEvent(of: .value) { (snapshot) in
// all of the code to get the posts information into another array to display on the collection view.
}
}

Sort an array of objects based on another array of objects in angular 7

I know it's been asked million+1 times. But i've found no help in those questions/answers.
I have 2 arrays of 2 different objects one string property is used to uniquely identify them. This would be the key to sort about, but said object prop names are not equal (accessValue, modifiedOption). But their values are!
Object1: { ... accessValue, ... };
Object2: { ..., modifiedOption, ... };
array1:Object1[];
array2:Object2[];
I'd like to sort array1 based on the object indencies of array2.
So all of array1 items'd be in the same order as array2.
These two arrays are used to model a connected dropdown selection system, which can be added to are removed from. The Addition is screwing me over (lastly added item is appended to the first place and not the last) probably because of filter below?
What I use to add new dropdowns:
addFieldRow() {
this.fieldRows.push(0); // since desired selection is not known yet but need to populate the array that represents the 1st selection so a 2nd main selection dropdown will appear on screen
...
}
public onSelect() {
// if a selection is happened check the values of editOptions (contains data about all main selectable options)
this.fieldRows = this.editOptions.filter(
option => this.selectedOptions.some(el => el.modifiedOption === option.accessValue)
);
this.disableSelected(); // disable already selected items (not related to my issue)
this.optionSelected = true; // this is just for button disabled toggle
}
So either i need to figure out my addRow logic (if it has any flaws) or implement a sorting utility to make sure that the objects of fieldRows are in the same order as selectedOptions' -> since this models the selection directly.
I cannot really add a stackblitz since it's hard to model my current state.
Okay I am a complete idiot!
Since I know the current index (since i am looping through fieldRows).
All I had to do is replace this:
public onSelect() {
this.fieldRows = this.editOptions.filter(
option => this.selectedOptions.some(el => el.modifiedOption === option.accessValue)
);
With this:
public onSelect(index) {
this.fieldRows[index] = this.editOptions.find(option => this.selectedOptions[index].modifiedOption === option.accessValue);
this.disableSelected();
this.optionSelected = true;
}
Now it works correctly.

How to Fetch a set of Specific Keys in Firebase?

Say I'd like to fetch only items that contains keys: "-Ju2-oZ8sJIES8_shkTv", "-Ju2-zGVMuX9tMGfySko", and "-Ju202XUwybotkDPloeo".
var items = new Firebase("https://hello-cambodia.firebaseio.com/items");
items.orderByKey().equalTo("-Ju2-gVQbXNgxMlojo-T").once('value', function(snap1){
items.orderByKey().equalTo("-Ju2-zGVMuX9tMGfySko").once('value', function(snap2){
items.orderByKey().equalTo("-Ju202XUwybotkDPloeo").once('value', function(snap3){
console.log(snap1.val());
console.log(snap2.val());
console.log(snap3.val());
})
})
});
I don't feel that this is the right way to fetch the items, especially, when I have 1000 keys over to fetch from.
If possible, I really hope for something where I can give a set of array
like
var itemKeys = ["-Ju2-gVQbXNgxMlojo-T","-Ju2-zGVMuX9tMGfySko", "-Ju202XUwybotkDPloeo"];
var items = new Firebase("https://hello-cambodia.firebaseio.com/items");
items.orderByKey().equalTo(itemKeys).once('value', function(snap){
console.log(snap.val());
});
Any suggestions would be appreciated.
Thanks
Doing this:
items.orderByKey().equalTo("-Ju2-gVQbXNgxMlojo-T")
Gives exactly the same result as:
items.child("-Ju2-gVQbXNgxMlojo-T")
But the latter is not only more readable, it will also prevent the need for scanning indexes.
But what you have to answer is why want to select these three items? Is it because they all have the same status? Because they fell into a specific date range? Because the user selected them in a list? As soon as you can identify the reason for selecting these three items, you can look to convert the selection into a query. E.g.
var recentItems = ref.orderByChild("createdTimestamp")
.startAt(Date.now() - 24*60*60*1000)
.endAt(Date.now());
recentItems.on('child_added'...
This query would give you the items of the past day, if you had a field with the timestamp.
You can use Firebase child. For example,
var currFirebaseRoom = new Firebase(yourFirebaseURL)
var userRef = currFirebaseRoom.child('users');
Now you can access this child with
userRef.on('value', function(userSnapshot) {
//your code
}
You generally should not be access things using the Firebase keys. Create a child called data and put all your values there and then you can access them through that child reference.

How to get a selected object within other stuff?

I have a multiselect grid where I can get schools.getSelectionModel().getSelection();
there is an object called data, I want to get a field within the data; lets say school_name
How I'll do it?
I've tried
schools.getSelectionModel().getSelection().data
schools.getSelectionModel().getSelection(data)
schools.datagetSelectionModel().getSelection()
they did not work.
You have to use Ext.each to iterate over the array of records..
Ext.each(schools.getSelectionModel().getSelection(), function(record, index, allRecords) {
console.log(record.get('school_name');
});
This:
schools.getSelectionModel().getSelection()[0].get('school_name')
should give you a 'school_name' field from first row selected (which is also a first record in selection).
To iterate over all selected rows do:
var selectedSchools = schools.getSelectionModel().getSelection();
for (i in selectedSchools) {
console.log(schools[i].get('school_name')); //this will log school name to firebug console - you can do whatever you need
}

Resources