Copying object properties to new/another object using AngularJS - javascript

I'm wondering what is the best way of copying object property's from/to another object using AngularJS/JavaScript
Below is the Json object I'm getting:
{
"application":{
"number":"323-23-4231",
"amount":"234.44",
"ref_name":"Thomas Edison"
},
"borrower":{
"prefix":"Mr",
"first_name":"Eric",
"middle_name":"E",
"last_name":"Schulz",
"date_of_birth":"09/29/1975",
"email_address":"myemail#HOTMAIL.COM",
"phones":[
{
"number":"(555)555-5555",
"type":"Mobile"
}
]
}
}
Using the above Json object I want the new JSON object data to be looks like this:
{
"number":"323-23-4231",
"amount":"234.44",
"ref_name":"Thomas Edison",
"prefix":"Mr",
"first_name":"Eric",
"middle_name":"E",
"last_name":"Schulz",
"date_of_birth":"09/29/1975",
"email_address":"myemail#HOTMAIL.COM",
"phones":[
{
"number":"(555)555-5555",
"type":"Mobile"
}
]
}

If you have the original object in a variable called oldObj, you could do something like this (untested):
newObj = {}
newObj = angular.extend(newObj, oldObj.application)
newObj = angular.extend(newObj, oldObj.borrower)
There are lots of ways to copy the properties of one object to another in different frameworks. Angular has the built-in angular.extend which you can read about here
You could even do this without using any fancy methods:
newObj.number = oldObj.application.number
newObj.amount = oldObj.application.amount
newObj.ref_name = oldObj.application.ref_name
newObj.prefix = oldObj.borrower.prefix
...
But that'd be kinda silly :)

Related

Is there a way to not include methods when converting an object to a json?

Right now, I'm trying to convert a object to a json, but the object has methods in it.
One common solution I've found is storing the function in the json, but that wouldn't work for me (mainly because that would totally break updating)
I think it will be easier to reinitialize the function every time the program is reloaded. What would be the best way to exclude functions when stringifying to json, but including the functions when the json is parsed?
Extra note: some of the functions are stored in arrays and other objects
Edit:
Current code to load json data:
var loadData = JSON.parse(window.localStorage.getItem("slotAuto"));
G = {
...G,
...loadData
};
Current code to save json data:
var toSave = JSON.stringify(G, G.ReplaceNull);
console.log(toSave);
window.localStorage.setItem("saveGame", toSave);
Replace Null function:
if (value == null) {
return undefined;
};
return value
Example object:
{
functionList: [function () {
console.log("do something")
}]
}
Example output:
{
"functionList": [null]
}

Setting JSON node name to variable value

I've spent most of my time in languages like Java and C++ but I'm trying to pick up JavaScript. What I'm attempting to accomplish is a way to set the parent node name by the value of the variable passed. I am using Firebase if that makes a difference in this code but I didn't think it would.
var parent_node_name = "EPLU200";
var onComplete = function(error) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
}
};
// update adds the data without replacing all of the other nodes
myFirebaseRef.update({
parent_node_name: { // trying to change this part to not save as "parent_node_name"
id2: "1175", // but instead as "EPLU200"
...
}
}, onComplete);
The action saves to my Firebase server just fine but the problem is passing the actual value of the variable instead of reading the variable name.
Is there any workaround in JavaScript? I tried searching for it but I didn't know what to call it.
Depending on the environment (i.e node?)
myFirebaseRef.update({
[parent_node_name]: {
id2: "1175",
...
}
}, onComplete);
See the code commented as Computed property names (ES6) in New Notations in ES2015 doumentation at MDN
if that doesn't work, you have to do this
var obj = {};
obj[parent_node_name] = {
id2: "1175",
...
};
myFirebaseRef.update(obj, onComplete);

Dojo: How to load an object (containing other objects) from JSON?

I have an object model that I want to be able to save. I am going to export it to JSON and then read it back in as JSON.
Saving to JSON is easy. Just use this: JSON.stringify(this).
Loading from JSON isn't as simple.
We can't just use this = JSON.parse(someJson) because the methods wont be attached.
Using something like lang.mixin(this, JSON.parse(someJson)) will get the functions but objects that are
Photo Class:
define([...], function(...){
return declare(null, {
name: ..., // String
url:..., // String
complexProperty:..., // Some other class
someFunction1: function(...){..},
someFunction2: function(...){..},
someFunction2: function(...){..}
}
));
Photo Album Class:
define([...], function(...){
return declare(null, {
photos: [], /* Array of type Photo (see above) */
someOtherProperty: ...,
someOtherProperty: ...,
someFunction1: function(...){..},
someFunction2: function(...){..},
someFunction2: function(...){..},
toJson: function(){
return JSON.stringify(this); // From dojo/json
}
loadFromJson: function(jsonIn){
// How to do this?
},
/* This doesn't work because methods will be overridden */
loadFromJson1: function(jsonIn){
this = JSON.parse(someJson);
},
/* This insures that my methods are kept intact but my childrens methods arn't (ie: the array of photos) */
loadFromJson2: function(jsonIn){
lang.mixin(this, JSON.parse(someJson));
},
/* This seems like an aweful lot of work. Any better ways to do this? */
loadFromJson3: function(jsonIn){
this.someOtherProperty = jsonIn.someOtherProperty;
this.someOtherProperty = jsonIn.someOtherProperty;
foreach(jsonIn.photos: photoJson){
var newPhoto = new Photo();
newPhoto.loadfromJson(photoJson);
this.photos.add(newPhoto);
}
... All other properties set recursively. All things in model now need this method ...
}
}
));
I think you would be better off returning a JSON object that contains just the data you need to serialize, not the whole class. Then your loadFromJson method would be a little easier to implement, and you wont be sending unnecessary data over the network. Example toJson():
toJson: function() {
return JSON.stringify({
photos: this.photos,
someImportantProp: this.someImportantProp,
anotherProp: this.anotherProp
});
}
JSON is not the same thing as a JavaScript object, in fact, it's only a subset. JSON only allows arrays, objects and of course basic types like Strings, booleans, numbers and null. You can find the entire specification here.
If you really want to keep the functions you can use the eval() function, but this is not really recommended, because it indeed parses those functions. If the evaluated content contains malicious input, then that is being executed as well.
For example:
eval("myObj = { getSum: function getSum(a, b) { return a + b; } }");
myObj.getSum(1, 2); // Returns 3
You can better attempt to save the state of the object (name and url for example) and rebuild it once you parse it again, that is what happens in other programming languages as well. For example, if you're serializing/deserializing an object in Java.

Accessing various elements in an array in Angular js

I am building an application using Angular js and Taffy DB.
javascript:
$scope.viewTable=function () {
$scope.resultlists=[];
$scope.resultSet=teamlist().get();
var teamdata=$scope.resultSet;
angular.forEach(teamdata,function(teamdata,i){
if (i<length) {
console.log(teamdata[i].text);
}
});
};
I have an array result from Taffy DB like this.
teamdata contains
[Object { text="zxcxzc", $$hashKey="00A", ___id="T000002R000002", more...}, Object { text="czxcz", $$hashKey="00C", ___id="T000002R000003", more...}, "zxczxc", Object { undefined={...}, ___id="T000002R000005", ___s=true}, 5454575, Object { undefined={...}, ___id="T000002R000007", ___s=true}, 2, 2727287.5]
and I have to display each element in a table.
How to access each element in the above array?
Please Advice
The signature of the angular.forEach for arrays is as follows:
angular.forEach(array, function(element) { ... })
So you should be able to access each row like that:
angular.forEach(teamdata, function(row) {
// ... row.text
});
angular.forEach documentation

delete JS Object attributes based on a JSON file

I have certain objects that I have to delete certain properties ie:
objA = { firstAttrA: 'fooA', secondAttrA: 'barA' }
objB = { firstAttrB: 'fooB', secondAttrB: 'barB' }
I want to pass these objects in a function that will delete the firstAttrA and firstAttrB based on the following properties file:
{
"objA":"firstAttrA",
"objB":"firstAttrB"
}
The method needs to be robust, I need to avoid excessive looping and anything that will affect performance since the amount of objects that will essentially be passed is great and their properties numerous.
Essentially i suppose I need to do a delete objA.firstAttrA; delete objB.firstAttrB; but driven by a JSON properties file.
Well if defined in the global scope then your method would look like this:
var objRef = {
"objA":"firstAttrA",
"objB":"firstAttrB"
};
for (var item in objRef) {
if (window.hasOwnProperty(item)) {
if (window[item].hasOwnProperty(objRef[item])) {
delete window[item][objRef[item]];
}
}
}

Categories

Resources