how to concat two json objects in angularJs - angularjs

I have the following in an angular controller:
var jsonOne = $cookies.get('test');
// console logs {"domain":"localhost","zip":33333}
var jsonTwo = angular.toJson($scope.formData);
// console logs {"id":"210","name":"sam"}
var final = $.extend(jsonOne, jsonTwo);
// console logs [object object]
My goal is to get:
var final
// console logs {"domain":"localhost","zip":33333, "id":"210","name":"sam"}
I'm asking under angular because when I try it in a static html document it works fine, but for some reason it wont work in angular. Any ideas?

The issue seems to be your use of angular.toJson, which from the docs serializes inputs as a JSON string. Using a string with angular.extend() won't work as you want.
Try to retrieve your elements without serializing them as a string - it seems like you might already have the objects and don't need to use .toJson.
Once you have your two objects, use angular.extend() to combine them.
var first = { "A": "B" };
var second = { "C": "D" };
var third = angular.extend(first, second);
console.log(third);
// in chrome it logs { A: "B", C: "D" }

Related

I am trying to push element into two arrays from an object. Returned undefined on the console in the Edge browser

I am working on an Angular project trying to push element into two arrays from an object. Returned undefined on the console (Edge browser). I did test the same code on the Visual Studio NodeJsConsole project, working fine.
Here is the code,
ngOnInit(): void {
this._salesDataService.getOrders()
.subscribe(res =>{
let data: any [] = [];
data.push(res);
let months: any [] = [];
let totals: any [] = [];
data.forEach(element => {
months.push(element.Month);
totals.push(element.totals);
});
console.log(data);
console.log(months);
console.log(totals);
});
}
Appreciate if someone can help me to figure this out - Thank You!
So there is a key difference in your code here. The VS example that works uses stubbed data (on line 4 of your image). The Angular code is subscribed to getOrders(). Inspect the data that comes in (defined for you as res) and you'll likely see a difference.
The arrays are not undefined, they have 1 element, at index 0, named undefined. In other words your code pushed undefined into each array, which means your res data is not as you expect.
Also your VS code uses element.Month and element.Total but your Angular code uses element.Month and element.totals - inconsistent.
From the first screenshot it looks like the result from the service, res, is an array. So you're pushing the res array into data array
Use res.forEach instead of data.forEach

Why is the array behaving like this

I am working on Angular 6 and i want to post an array of JSON objects using a service class.
The following is my function
getrerun(data,file){
this.post=[];
for(var i=0;i<data.length;i++)
{
this.rerun.storeno=data[i].storeNo;
this.rerun.filetype=data[i].loadtype;
this.rerun.outboundsystem[0]=file;
this.rerun.createdate=data[i].createdDate;
this.post[i]=this.rerun;
console.log("------>"+JSON.stringify(this.rerun)+"------->"+JSON.stringify(this.post));
}
this.newurl=this.devurl+"rerun";
return this.http.post<any>(this.newurl,this.post);
}
newurl is the url of the rest api that i want to hit and this.post is the array that i am sending
The value of data is following:
[{"lastDate":"2019-02-20 12:36:27","storeNo":"G015","country":"SG","serviceStatus":"FAIL","createdDate":"2019-01-04 11:53:56","loadtype":"F"},{"lastDate":"2019-02-20 10:54:00","storeNo":"G121","country":"SG","serviceStatus":"FAIL","createdDate":"2019-01-23 16:29:33","loadtype":"F"}]
and file is 'TP';
However the post array that I am getting is this:
[{"outboundsystem":["TP"],"storeno":"G121","filetype":"F","createdate":"2019-01-23 16:29:33"},{"outboundsystem":["TP"],"storeno":"G121","filetype":"F","createdate":"2019-01-23 16:29:33"}]
this basically means that both the entries in the array are the same i.e this.post[0].storeno is same as this.post[1].storeno. However, they should have two different values.
What do I do about this?

Problems with parsing a JSON Array after retrieving from firebase when using ionic-selectable

I'm currently developing an App using Ionic 3 and Firebase. I'm using ionic-selectable (you can see my stackblitz here) for the user to select an option from my firebase database array and return the selected option to the user's id.
I have got everything to work, except that ionic-selectable is not reading the retrieved array form firebase.
I'm retrieving the array using the following code:
this.itemsRefdiag = afg.list('medicalhx');
this.items = this.itemsRefdiag.snapshotChanges().map(changes => {
return changes.map(c => ({ ...c.payload.val() }));
});
const dgRef = this.afg.database.ref();
dgRef.child('medicalhx').orderByChild('name').on('value', snapshot => { this.snapshot2 = JSON.stringify(snapshot).replace(/"[0-9]":{"name":|{|}/g, ""); })
My console.log results in:
"Hyperthyroidism","Hypothyroidism","Diabetes Type 1","Diabetes Type 2"
However, when using ionic-selectable for private diagnoses: Diagnosis[] = [this.snapshot2], I get 'undefined' options. However, when I manually type in private diagnoses: Diagnosis[] = ["Hyperthyroidism","Hypothyroidism","Diabetes Type 1","Diabetes Type 2"], it works. I also tried parsing the JSON array using the following code instead:
this.itemsRefdiag = afg.list('medicalhx');
this.items = this.itemsRefdiag.snapshotChanges().map(changes => {
return changes.map(c => ({ ...c.payload.val() }));
});
const dbRef = this.afg.database.ref();
dbRef.child('medicalhx').orderByChild('name').on('value', snapshot =>
{ let snapshot3 = JSON.stringify(snapshot).replace(/"}/g, `"`);
let snapshot4 = snapshot3.replace(/"[0-9]":{"name":|{|}|"/g, "");
this.snapshot2 = snapshot4.split(",");
});
My console.log results in an Object with separate strings (an array):
["Hyperthyroidism","Hypothyroidism","Diabetes Type 1","Diabetes Type 2"]
However, ionic-selectable still doesn't seem to read that and I get undefined error. Any ideas on what I may be doing wrong with the array?
EDIT
It actually does work the second time around, however the console error pops up the first time and I believe this is because it's not waiting for the array results to pop-up the first time around. Is there a way to add a wait time until the array loads?
The second code listed in the question converting it to a real array worked but required a loading time, hence poping up a console error. I managed to get around the loading time issue by implementing Asynchronous searching as per this stackblitz.

Append new JSON objects to an array in Polymer

I am using a REST API to fetch an array of objects in a Polymer 2.0.2 project. The response is something like this:
[
{"name":"John","city":"Mumbai"},
{"name":"Ron","city":"New York"},
{"name":"Harry","city":"Lisbon"}
]
When the response is received, I set my property named content as follows:
_contentAjaxResponseHandler(event) {
this.set('content', event.detail.response);
}
This works as long as the REST API is called once.
Now, I want to fetch the next batch when user scrolls to the bottom of the page and add it to the existing data.
So, my question is, what is the best way to append new result to the existing content array? Or in other words, What is the best way to merge 2 arrays in polymer?
Till now, the only way I can think of is to loop over the new result and call push method.Something like this:
_contentAjaxResponseHandler(event) {
let newResponse = event.detail.response;
newResponse.forEach(function(newObj){
this.push('content',newObj);
});
}
The following code worked for me:
_contentAjaxResponseHandler(event) {
let newResponse = event.detail.response;
this.set('content',this.content.concat(newResponse));
}

convert string in given format to knockout observable array

I have the following string comming from server (as part of object):
...
SelectValues: "[{displayName: "Not selected", id: 0},{displayName: "Client", id: 1},{displayName: "Industry", id: 2},{displayName: "Country", id: 3}]"
...
I am using mapping pluging:
var ItemModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
}
As a result all items are created properly, except SelectValues. SelectValues should be observable array (each array item should have two properties id & displayName). Later I will use SelectValues for dropdown.
The problem is that it is returned as String and not as Array.
The question is whether I can somehow deal with it on client side (without changing format on server side)?
I probably can create SelectValuesComputed as ko.computed and somehow convert SelectValues to array (how?).
First of all, this is invalid JSON string you have in your property, see documentation (property names should be in quotes). But, having the condition that you cannot change the server code, you can use eval function to get your object and then use it in mapping like this:
var ItemModel = function (data) {
var self = this;
var mapping = {
"SelectValues": {
create: function(options){
return ko.mapping.fromJS(eval(options.data));
}
}
};
ko.mapping.fromJS(data, mapping, self);
}
See working demo. Although this might seem like the simpliest way to workaround the problem, I would strongly recommend you though to get a valid JSON string instead of using eval (or regexp) to get your object.

Resources