AngularJS dynamic scope variables - json

I have a scope variable jsonData as below:
$scope.jsonData={id:'1234',abcd:{array:[{a:'data',b:'bdata',c:'cdata'},{a2:'a2data',b2:'b2data',c2:'c2data'}]},efg:{test:'testdata'}}
in my HTML I have a function calladd('jsonData.abcd.array') with a string
in my js file I want to add an JSON object to arrayinside the abcd JSON object
$scope.add(data) {
$scope[data].push({a3:'a3data',b3:'b3data',c3:'c3data'});
}
but I am unable to push data into array.

If you wanted to get ID, you can do
var id = $scope.jsonData.id;
//id = "1234"
You can use the same logic to add or get values

Calling myobject['prop1.prop2.whatever'] just doesn't work.
What you need is a recursive parser like :
$scope.add = function(data, scope){
scope = (typeof scope === "undefined") ? $scope : scope;
var datas = data.split('.');
if(datas.length == 1){
scope[datas[0]].push({
a3: 'a3data',
b3: 'b3data',
c3: 'c3data'
});
}else{
var first = datas.splice(0,1);
$scope.add(datas.join('.'), scope[first]);
}
};
And the fiddle

Related

What does this conf do?

So I was looking at a tutorial online and came across this:
function generateRobot(conf:Object = null):Robot {
var conf:Object = conf || {};
var defaults:Object = {
laserColor:red,
personality: "evil"
}
for (var key:String in defaults){
conf[key] = conf[key] || defaults[key];
}
Can someone help explain what line 2 and line 8 mean? Thanks for helping a new coder!
I have added some comments and renamed the param to make it clearer:
//param is a parameter of the type object with a default value of null that is passed
//into the function, if nothing is passed in it will be null
function generateRobot(param:Object = null):Robot {
//declare a local variable called conf and populate
//it with the parameter if it exists, otherwise create a new object {}
var conf:Object = param || {};
//create a default settings object
var defaults:Object = {
laserColor:red,
personality: "evil"
}
//loop through the default settings
for (var key:String in defaults){
//conf setting becomes param if exists otherwise use the defaults value
conf[key] = conf[key] || defaults[key];
}
The questions seems specific to the || construct in the variable assignment. As #Thilo mentioned, it is simply a way to specify a default, should the field be missing in the parameter.
For example:
function read_file(file, delete_after) {
delete_after = delete_after || "False";
//rest of code
}
would be such that, if variable delete_after is not passed when function read_file is called, then it will assume value "False", or anything after the || sign.
Some prefer an explicit check against undefined.
Other pointers to look at:
Set a default parameter value for a JavaScript function
http://www.codereadability.com/javascript-default-parameters-with-or-operator/

Nodejs breeze-sequelize with MySQL - .select() not functioning

I'm using breeze-sequelize version 0.0.18. I get a bizarre error _.pluck is not a function when I try to use select() on the entityQuery. And if I remove .select(), it'll work just fine.
My breeze query looks like this:
var predicate = Predicate.create('transactionDate', '>=', fromDate);
var entityQuery = EntityQuery.from('Transactions')
.where(predicate)
.select('transactionDate');
var sequelizeQuery = new SequelizeQuery(api.db, entityQuery);
return sequelizeQuery.execute();
And upon return, the error I get is:
TypeError: _.pluck is not a function
at SequelizeQuery.<anonymous> (/Users/shu/Documents/project/node_modules/breeze-sequelize/SequelizeQuery.json.js:143:39)
at Array.map (native)
at SequelizeQuery._processSelect (/Users/shu/Documents/project/node_modules/breeze-sequelize/SequelizeQuery.json.js:136:56)
at SequelizeQuery._processQuery (/Users/shu/Documents/project/node_modules/breeze-sequelize/SequelizeQuery.json.js:72:8)
at new SequelizeQuery (/Users/shu/Documents/project/node_modules/breeze-sequelize/SequelizeQuery.json.js:43:23)
at getTransactions (/Users/shu/Documents/project/src/server/api/admin.controller.js:189:26)
So curiously I took a look at function SequelizeQuery._processSelect in my breeze-sequelize library. The error is coming from return usesNameOnServer ? pp : _.pluck(props, "nameOnServer").join(".");.
SequelizeQuery.prototype._processSelect = function() {
var selectClause = this.entityQuery.selectClause;
var usesNameOnServer = this.entityQuery.usesNameOnServer;
if (selectClause == null) return;
// extract any nest paths and move them onto the include
var navPropertyPaths = [];
this.sqQuery.attributes = selectClause.propertyPaths.map(function(pp) {
var props = this.entityType.getPropertiesOnPath(pp, usesNameOnServer, true);
var isNavPropertyPath = props[0].isNavigationProperty;
if (isNavPropertyPath) {
this._addInclude(this.sqQuery, props);
}
if (isNavPropertyPath) return null;
return usesNameOnServer ? pp : _.pluck(props, "nameOnServer").join(".");
}, this).filter(function(pp) {
return pp != null;
});
}
Can someone help me? Thanks!
The _.pluck function is from lodash, and lodash removed the pluck function in version 4.0
The breeze-sequelize library will eventually be updated to lodash 4, but in the meantime, try using lodash 3.x.

json each parser ajax

I receive json information as:
{"entInfos":[{"conent":"entreprise","conadd":"45 rue de Paris","conadd2":"75010 \/ Paris| France"}]}
I need to extract each item for entInfos conent = entreprise, conadd = 45 ... etc ...
I tried, but isn't working.
Below is what I tried. Do, you have sample or idea ?
var json = JSON.parse(response);
$.each(json, function(i, item) {
alert(item.conadd);
alert(i.conadd);
});
you probably forgot about entInfos object:
var json = JSON.parse(response);
json.entInfos.forEach(function(info) {
alert(info.conadd);
alert(info.conadd2);
alert(info.conent);
});
And instead of jQuery's $.each method, I've just plain JavaScript's (ES5) forEach method.
Does this help?
Auto response :
var json = JSON.parse(response);
$(json.entInfos).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" ===== "+ v);
});
});

How to create an object of specific type from JSON in Parse

I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible

ParseJSON with functions to javascript object

I have a problem that seems complicated that I don't know how to solve.
My single page application uses knockoutJS and I want to cache my view model every time one of my input values change on my view.
Where the problem lies is the complexity of my view model. To use local storage I need to stringify my object but it has recursive values. I have some logic to handle this and stringify my object. But when I try to parse the JSON string back to an object, I lose my functions.
function cacheForm(agency) {
//var serialized = stringifyOnce(agency);
//var serialized = amplify.store("Agency", agency);#
//var obj = new Object();
//obj.test = "test";
value = agency;
var cache = [];
parsed = JSON.stringify(value, function (key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
//var jsonString = JSON.stringify(cache);
//cache = null; // Enable garbage collection
var parsedRecursive = "{" + '"data"' + ":" + parsed + "," + '"expires"' + ":" + null + "}"; // Build the string based on how amplify likes it
var obj = eval('(' + parsed + ')')
var obj = jQuery.parseJSON(parsedRecursive);
//// Put the object into storage
//localStorage.setItem('Agency', parsedRecursive);
myData = JSON.parse(parsedRecursive, function (key, value) {
var type;
if (value && typeof value === 'object') {
type = value.type;
if (typeof type === 'string' && typeof window[type] === 'function') {
return new (window[type])(value);
}
}
return value;
});
//// Retrieve the object from storage
// var retrievedObject = localStorage.getItem('Agency');
// var obj = jQuery.parseJSON(parsedRecursive);
//var agency2 = mapping.fromJS(obj);
//agency;
//amplify.store("Agency", agency);
//amplify.store("Obj", obj);
//var store = amplify.store(); // Look at all items by not providing a key
}
});
I tried using eval but this returned an object without my data. To help you understand this is what my view model looks like, which is the agency parameter of cachForm.
Also I tried using amplify but because of my view model structure I run into the same issue.
I have also attached some screenshots to show what happens with my viewmodel in the code.
It is not a good idea to cache the whole viewModel. A viewModel contains observables, computeds and functions or events handlers.
You have better to cache the view model data, only the raw data.
On serialization :
So just serialize the view data (use ko.mapping.toJSON):
var json = ko.mapping.toJSON(viewModel);
In order to rebuild a proper view model it is better to have a initialisation function.
This is your view model constructor e.i. a function that adds the event handlers, functions and computed.
var initializer = your_constructor;
You also need to determine a cache key e.g. the page path.
var cacheItem = {data : json, constructor : initializer};
cache[key] = cacheItem;
On deserialization :
Get the cache item :
var cacheItem = cache[key];
var viewModel = JSON.parse(cacheItem.data);
Now viewModel contains the raw data.
viewModel = ko.mapping.fromJS(viewModel);
The properties were converted into observables.
If there is a constructor call it.
if(cacheItem.constructor)
cacheItem.constructor.call(viewModel);
Then your view model is as you stored it.
I hope it helps.
This is the answer I have posted in another post. They are both related.
JSON.parse returns children objects with null value, children values not being parsed