Modifying certain fields in array of objects - angularjs

I get some objects from a server that look like this:
{
"id": 1",
"name": "Jim"
}
I toss them in $scope.myThings, modify them in my app, adding some fields, they end up looking like this:
{
"id": 1",
"name": "Jim",
"favoriteFood": "Noodles"
}
Perhaps I get an update from the server, changing Jims name. I'd like to take the array of objects I get back from the server and apply their changes to the list that's in $scope without having to replace the list entirely (ie: $scope.myThings = newData) or having to iterate through comparing IDs.
Is there a method to do this?

You can use angular.merge.
It's working with object and arrays.
usage
angular.merge(dst, src);
dst Object Destination object.
src Object Source object(s).
For example:
var a = [{x:4}]; var b=[{x:2,y:3}]; angular.merge(a,b);
result:
a=[{x: 2,y: 3}]
var a = [{x:4}]; var b=[{x:2,y:3}]; angular.merge(b,a);
result:
b=[{x: 4,y: 3}]

Related

How to create this JSON response?

I'm trying to Create a specific Syntax for POST Request.
That is, using Javascript to Create the specified Array Structure based on certain data.
Data : Array of Objects. Each Object represents a row in a Table.
Those rows, have an ID Key, that can be found on More that one Row.
POST Request : Create the Below POST Request Syntax:
For Each Unique Row ID, create the P1 Section. (This Object Represents each Unique ID )
If ID is entered more that once, do not create more P1 Sections with same ID. P1 is already created for this ID.
For each of these unique IDs, get its Row Details and place them in Section P2.
If Unique IDs rows are more that one, create multiple P2 Sections for the Specific ID.
[
[
P1 - {
"Swee": "Cont",
"Time": 33,
"ID": 10,
"Configs": [
P2 - {
"VAL": "VALUE"
P2 - }
]
P1 - }
]
]
Please, anyone can help please do.
I would recommend the following:
1. Iterate over your data and filter what you need, simplest is to use lodash try this method for your needs: https://lodash.com/docs/4.17.11#uniqBy
2. You can deconstruct properties and elements from an object or array like this this:
const { property1, property2, property3 } = this.myData this exposes these properties from your data (stored in myData in this example), now you can restructure them as you wish for example:
paylod : { property1: { property2 }, property3 } here my payload object now has a new nested structure. In your question you do not provide enough info for me to do this but this would be a direction to take. Hope this helps

How can I remove items from a JSON array based on a list of array keys?

I'm trying to build an API in node.js that syncs two different systems, and I'm having trouble breaking down an array of objects I receive from my source system.
Basically, I receive an array that looks a bit like this:
sourcedata = {
"items": [
{ "id": "item1",
"some fields": {...array of some fields },
"more fields": {another block of fields}
},
{ "id": "item2",
"some fields": {...array of some fields },
"more fields": {another block of fields}
}]
}
What I also have are three arrays of IDs - new ones (means I have to send them to the target system), old ones (to delete from the target), and ones that appear on both - those I need to check a special tag to see if they are different or not.
e.g.
newitems = [id1,id2,id3]
existingItems [id4,id5,id6]
deletedItems = [id7,id8]
What I'm trying to do is create new arrays that will only contain the data of the NEW and EXISTING items, so I can process and send them over to the target system without scanning the sourcedata array for each key and deciding what to do . I know how to do that when I compare simple arrays, but here I need the entire objects and all its fields copied over, and I can't
find the proper way to do it. Any help would be appreciated.
You can make use of the filter function. It filters out elements of array based on your condition. You may use it with the includes function to determine if a thing is in an array. For example:
sourceArray = [
{
id: 'a'
},
{
id: 'b'
},
{
id: 'c'
},
{
id: 'd'
}
]
var toDelete = ['c', 'b']
sourceArray = sourceArray.filter(x => !toDelete.includes(x.id))
// some items in sourceArray have now been removed.
Note that filter and includes may require a recent version of nodejs.

How do I import my JSON array into Firebase as a FirebaseArray?

I have a large JSON file which contains an array. I am using Firebase for my app's backend and I want to use FirebaseArray to store the data.
It is simple to create a FirebaseArray from my Angular app and add data to it, but the nature of my app is that I have fetched data which I need to first import into Firebase somehow.
On the Firebase website the only option for importing is from a JSON. When I import my JSON file, the result is an object with numerical keys, which I realize is like an array, but has a major issue.
{
"posts": {
"0": {
"id": "iyo0iw",
"title": "pro patria mori"
},
"1": {
"id": "k120iw",
"title": "an english title"
},
"2": {
"id": "p6124w",
"title": "enim pablo espa"
}
}
}
Users are able to change the position of items, and the position of an item is also how items are uniquely identified. With multiple users this means the following problem can occur.
Sarah: Change post[0] title to "Hello everyone"
Trevor: Swap post[1] position with post[2]
Sarah: Change post[1] title to "This is post at index 1 right?"
If the following actions happen in a short space of time, Firebase doesn't know for sure what Sarah saw as post[1] when they changed the title, and can't know for sure which post object to update.
What I want is a way to import my JSON file and have the arrays become FirebaseArrays, not objects with numerical keys, which are like arrays and share the issue described above.
What you imported into your database is, in fact, an array. Firebase Realtime Database only really represents data as a nested hierarchy of key/value pairs. An array is just a set of key/value pairs where the the keys are all numbers, typically starting at 0. That's exactly the structure you're showing in your question.
To generate the sort of data that would be created by writing to the database using an AngularFire FirebaseArray, you would need to pre-process your JSON.
Firebase push IDs are generated on the client and you can generate one by calling push without arguments.
You could convert an array to an object with Firebase push ID keys like this:
let arr = ["alice", "bob", "mallory"];
let obj = arr.reduce((acc, val) => {
let key = firebase.database().ref().push().key;
acc[key] = val;
return acc;
}, {});

How to traverse the following JSON in angularJS

So i am recieving a JSON string from a rest service which has the following structure-
{
"map": {
"Project [projectId=1, projectName=Project1]": [
{
"employeeId": 4,
"employeeName": "fourthEmployee"
}, {
"employeeId": 3,
"employeeName": "thirdEmployee"
}
],
"Project [projectId=2, projectName=Project2]": [
{
"employeeId": 4,
"employeeName": "fourthEmployee"
}
]
}
}
( for reference, this is the object type being made available by rest - Map<Project,List<Employee>>)
My question is, how do i display the data from this particular JSON onto the HTML page in the form of a table, using angularJS?
I do realise ng-repeat is to be used multiple times. Its just that using ng-repeat, i'm not able to get the values from JSON. Could someone reply with code, that would be really helpful thanks.
EDIT: As pointed out by Robert, the problem is i am unable to get values from the compound project data. Help is appreciated. Thanks.
Based on insufficient data let me provide a solution to the problem that I speculate OP is actually having.
Compound project data problem
I suspect that the main problem you're having is not about using nested ngRepeat but parsing the compound data of your projects.
This means that before you try displaying your data, you have to parse it or re-map it to something that you can actually use in your view.
This example uses regular expression to parse individual project property values.
var rx = /^Project \[projectId=(\d+), projectName=(.+)\]$/i;
var result = [];
for(var p in data.map)
{
if (data.map.hasOwnProperty(p) && rx.test(p))
{
var m = rx.exec(p);
result.push({
id: m[1],
name: m[2],
employees: data.map[p]
});
}
}
This is a working Fiddle with your provided data that displays projects including their data.

How to get database field values from extbase action?

now that I managed to get random AJAX output, I want to get some useful values from the database as the next step.
Once again, my AJAX call looks like this (additionally, I added a JSON call, which would be even better).
$.ajax({
url: "index.php",
data: "tx_myext_myplugin1[controller]=Mycontroller1&tx_myext_myplugin1[action]=ajax&type=89657201",
success: function(result) {
alert(result);
}
});
/*
var uri = '<f:uri.action action="ajax" controller="Mycontroller1" pageType="89657201" />';
jQuery.getJSON(uri, function(result) {
alert(result.c);
});
*/
my ajaxAction function:
public function ajaxAction() {
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
return json_encode($arr);
}
This works when I use the JSON call, now I need to get an array with database values though. I thought calling the repository with a findAll() function would already help, but it's not an array I think, which is why I can't use it. A different idea would be to use the getValue methods I wrote in the Model, but I'm not sure if this would help.
Disclaimer: Generally using findAll() method can be real performance killer therefore try to write custom finders, selecting only required properties, especcialy if your model is big or contains many relations!
You are close enough, as you can send findAll() result with json_encode(), but be careful, depending on your model, json created from findAll can be really huge. It's better idea to iterate results and rewrite to new array only required values.
$dataFromRepo = $this->yourRepository->findAll();
$resultArray = array();
foreach ($dataFromRepo as $object){
$resultArray[$object->getUid()] = $object->getTitle();
}
return json_encode($resultArray);
in result you'll get basic JSON object:
{
"1": "Title of first item",
"2": "Second item",
"3": "Et cetera"
}
When you'll remove custom index from $resultArray
foreach ($dataFromRepo as $object){
$resultArray[] = $object->getTitle();
}
you will get JSON array
[
"Title of first item",
"Second item",
"Et cetera"
]
And so on. Of course you can also build this way multidimensional array and send more sophisticated objects to get all you need at once.
P.S. Try always to use for an example JsonLint - online validator to validate if the output you're expecting is valid.

Resources