Merge dynamic object arrays in javascript - javascript

I'm trying to dynamically build an object with key:[value array], however using different methods I keep ending up with a singular item in the value array (where in the response there are multiple values).
Psuedocode:
var myFunction = function () {
var myObject = {};
$.ajax('http://the.url.com', {
type: "GET",
success: function (res) {
$(res).each(function (i, v) {
var name = v.name;
var id = v.id;
// create object with building block and tech id to associate techs to BBs
myObject[name] = new Array();
myObject[name].push(id);
});
},
error: function (xhr) {}
}
}
Current output:
{
key1: ["value1c"]
key2: ["value2a"]
key3: ["value3b"]
}
Desired output:
{
key1: ["value1a", "value1b","value1c"]
key2: ["value2a"]
key3: ["value3a", "value3b"]
}

You're overwriting the existing array with a new one for each key, then pushing the latest one in with the following line:
myObject[name] = new Array();
Try adding a check to avoid overwriting:
myObject[name] = myObject[name] || new Array();

The out put is key1: ["value1c"] since key in an object is unique, so it is creating key and storing only latest value. You can use hasOwnProperty and check if myObject has any key by that name. If so then push the value, else create a key value pair and add id to it
$(res).each(function(i, v) {
var name = v.name;
var id = v.id;
if (myObject.hasOwnProperty(name)) {
myObject[name].push(id);
} else {
myObject[name] = [id];
}
});

I think that you need to check if myObject[name] already exists before creating a new one. Because if you create a new one each time, it will be overridden
var myFunction = function () {
var myObject = {};
$.ajax('http://the.url.com', {
type: "GET",
success: function (res) {
$(res).each(function (i, v) {
var name = v.name;
var id = v.id;
// create object with building block and tech id to associate techs to BBs
if (!myObject[name]) {
myObject[name] = new Array();
}
myObject[name].push(id);
});
},
error: function (xhr) {}
}
}

You create another array each time with this line :
myObject[name] = new Array();
So you delete the old pushed value each time.
Use a condition to initialize your array if not exist :
!Array.isArray(myObject[name]) && (myObject[name] = new Array());
e.g.
$(res).each(function(i, v) {
var name = v.name;
var id = v.id;
// create object with building block and tech id to associate techs to BBs
!Array.isArray(myObject[name]) && (myObject[name] = new Array());
myObject[name].push(id);
});

Related

How to read JSON Response from URL and use the keys and values inside Javascript (array inside array)

My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});

How to make a copy of a Parse Object in the Cloud?

I would like to have a copy if an existing Parse Object, and then make some edits and save it as a new Parse Object rather than setting each field manually.
Here is my cloud function :
Parse.Cloud.define("SharePost", function(request, response) {
var ShareUserID=request.params.ShareUserID;
var UserID=request.params.UserID;
var PostID=request.params.PostID;
Parse.Cloud.useMasterKey();
var user = new Parse.User({id:UserID});
var shareuser = new Parse.User({id:ShareUserID});
var query = new Parse.Query("Feed");
query.get(PostID, {
success: function(post) {
var Post = Parse.Object.extend("Feed");
var newpost = new Post()
// here I would like to get the same object and make some edits o, it
post.save( {
success:function () {
response.success("Success");
},
error:function (pointAward, error) {
response.success(error);
}
}
);
},
error: function(error) {
console.error("Got an error " + error.code + " : " + error.message);
}
});
});
There might be a prettier way, but one way that's sure to work without relying on any subtleties would be this:
function pfClone(fromObject, toObject, keys) {
var _ = require('underscore');
_.each(keys, function(key) {
toObject.set(key, fromObject.get(key));
});
}
call it like this:
// after fetching a post called "post"
var Post = Parse.Object.extend("Feed");
var newpost = new Post();
var keys = ["title", "author" /* ...the keys you want to copy unchanged */ ];
pfClone(post, newpost, keys);
// change other properties of newpost here
Even prettier would be a version that introspects on the passed object, and then builds and initializes the clone. The one inelegance for either of these ideas is that (last time I checked) PFObject doesn't let you introspect the keys, so you're stuck passing in an array of keys.

Javascript : How to concat string to object?

I have following code where i combine some variables to create path to the another existing object and his attribute.
Problem is that i alway get only string, so i would like to "convert" it into the object.
// SET CUSTOM CONTENT FOR COLUMN IF CONTACT ATTR IS EXISTS
if(value.concatByFields != null) {
preparedGridColumnItem.template = function (responseData) {
var nameForConcat;
var fieldName;
var objectName;
var pathToReturn;
$.each(value.concatByFields, function( index, concatField ) {
nameForConcat = null;
fieldName = null;
objectName = null;
objectName = value.field;
fieldName = concatField.fieldName;
console.log("FIELD NAME IS");
console.log(JSON.stringify(fieldName));
console.log("OBJECT NAME IS");
console.log(objectName);
nameForConcat = objectName+"."+fieldName;
console.log("CONCATED NAME IS");
console.log(nameForConcat);
console.log("OBJECT ADDRESS IS FOLLOWING");
console.log("responseData."+nameForConcat);
pathToReturn = "responseData."+nameForConcat;
});
//TODO : IS ALWAYS RETURNED AS STRING
return pathToReturn;
};
}
Returned value should be value of another and global existing json object. But now is it always string.
It means:
responseData.SomeObject.surname
How can i solve it please?
Many thanks for any help.
if(value.concatByFields != null) {
preparedGridColumnItem.template = function (responseData) {
var fieldName;
var objectName;
var pathToReturn;
$.each(value.concatByFields, function( index, concatField ) {
objectName = value.field;
fieldName = concatField.fieldName;
pathToReturn = responseData[objectName][fieldName];
});
//TODO : IS ALWAYS RETURNED AS STRING
return pathToReturn;
};
}

Why does updating properties in one object change another object?

I'm loading JSON data into an object via ajax, copying that object to new objects (initData and newData). When I change the property of newData, the property of initData also changes. Why is this happening?
var initData = {};
var newData = {};
function load_data(NDB_No){
$.getJSON(('scripts/jsonencode.php?q=' + NDB_No), function(data) {
for (prop in data){
initData[prop] = data[prop];
newData[prop] = data[prop];
}
console.log('init data: ' + initData.properties.Protein); // "init data: 0.259"
console.log('new data: ' + newData.properties.Protein); // "new data: 0.259"
var n = parseFloat(newData.properties.Protein);
newData.properties.Protein = n+1;
console.log('init data: ' + initData.properties.Protein + 'new data: ' + newData.properties.Protein);
// "init data: 1.259 new data: 1.259"
// why are these the same when I only updated newData object?
});
}
It looks like data[prop] is an object (since you are later referring to newData.properties.Protein). Objects are always passed by reference, with the variable just being a pointer to it.
Since you're getting JSON in the first place, your object is JSON-able, so you can use that to "clone" the object:
$.getJSON(...,function(data) {
initData = JSON.parse(JSON.stringify(data));
newData = JSON.parse(JSON.stringify(data));
});
This will ensure that the objects are separate. There are other ways to do this, but this one avoids the manual recursion by using built-in methods (always faster)
This sets both to reference the same memory space:
initData[prop] = data[prop];
newData[prop] = data[prop];
...so when you change newData, you also change initData. Instead of assigning by reference, you'll want to create a copy. I have to run, so I can't provide an example of that right now.

Is there a Jquery function that can take a #ref id value from a parsed JSON string and point me to the referenced object?

I have been looking for an answer to this all afternoon and i cant seem to find the best way to accomplish what i need to.
My JSON string (returned from a web service) has circular references in it (#ref) which point to $id in the string. Now i know that if use jquery parseJSON it creates the javascript object and i can access properties a la myObject.MyPropertyName. However, when i get to a #ref, i am unsure how to get the object that ID points to (which i assume is already created as a result of the de-serialization...
Should i be iterating though the object and all its child objects until i find it, or is there an easier way?
$.ajax({
type: "POST",
url: "/Task.asmx/GetTask",
data: "{'id':'" + '27' + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
_Data = $.parseJSON(msg.d ? msg.d : msg);
_this.Company = _Data[0].t_Program.t_Company;
_this.Program = _Data[0].t_Program;
_this.Task = _Data[0];
},
complete: function () {
}
});
The area in question is _Data[0].t_Program because it does not return an object but rather returns
_Data[0].t_Program
{...}
$ref: "12"
I dont exactly know the best way to get the object with $id "12". Based on the posts below it seems i should loop through the existing object, but i was hoping there was a jquery function that did that...
Many Thanks!
No, jQuery is not natively capable of resolving circular references in objects converted from JSON.
The only library for that which I know is Dojo's dojox.json.ref module.
But, your server application serializes that JSON somehow. Don't tell me that the solution it uses does not offer a deserialisation algorithm!
As my friend Alan, the author of the Xerox Courier (RPC over the net) library, used to say to me, "there are no pointers on the wire."
In other words, it is impossible for a JSON representation of a data structure to be circular. (But a circular structure can be flattened into a non-circular JSON structure.) As the JSON site says:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
No pointers!
So the entire JSON will have been turned into Javascript Objects and/or Arrays after the jQuery parseJSON operation completes.
If the original stucture's ref_id values were used as the property names in the JSON / Javascript object, then they'll all be there.
The real issue is that you need to understand how your server serialized its data structure into the JSON data structure. Look in your server-side code to determine that.
Then use Javascript to de-serialize the JSON structure back into the best Javascript structure to fit your needs.
Re: Should i be iterating though the object and all its child objects until i find it, or is there an easier way?
The easier way would be to go through the Javascript structure once, and build up an additional "indexing" object whose properties are the #ref_id and the values are the original structure/value.
Sample:
var jsonCyclicReferenceFixed = JsonRecursive.parse(jsonWithRefAndId);
(function(){
function type(value){
var t = typeof(value);
if( t == "object" && value instanceof Array) {
return "array";
}
if( t == "object" && value && "$id" in value && "$values" in value) {
return "array";
}
return t;
}
function TypeConverterFactory(){
var converters = {};
var defaultConverter = {
fromJson: function(value){ return value; },
toJson: function(value){ return value; },
};
this.create = function(type){
var converter = converters[type];
if(!converter) return defaultConverter;
return converter;
};
this.register = function(type, converter){
converters[type] = converter;
converter.valueConverter = this.valueConverter;
};
}
function ObjectConverter(){
this.fromJson = function(obj){
if( obj == null ) return null;
if( "$ref" in obj ){
var reference = this.dictionary[obj.$ref];
return reference;
}
if("$id" in obj){
this.dictionary[obj.$id] = obj;
delete obj.$id;
}
for(var prop in obj){
obj[prop] = this.valueConverter.convertFromJson(obj[prop]);
}
return obj;
}
this.toJson = function(obj){
var id = 0;
if(~(id = this.dictionary.indexOf(obj))){
return { "$ref" : (id + 1).toString() };
}
var convertedObj = { "$id" : this.dictionary.push(obj).toString() };
for(var prop in obj){
convertedObj[prop] = this.valueConverter.convertToJson(obj[prop]);
}
return convertedObj;
}
}
function ArrayConverter(){
var self = this;
this.fromJson = function(arr){
if( arr == null ) return null;
if("$id" in arr){
var values = arr.$values.map(function(item){
return self.valueConverter.convertFromJson(item);
});
this.dictionary[arr.$id] = values;
delete arr.$id;
return values;
}
return arr;
}
this.toJson = function(arr){
var id = 0;
if(~(id = this.dictionary.indexOf(arr))){
return { "$ref" : (id + 1).toString() };
}
var convertedObj = { "$id" : this.dictionary.push(arr).toString() };
convertedObj.$values = arr.map(function(arrItem){
return self.valueConverter.convertToJson(arrItem);
});
return convertedObj;
}
}
function ValueConverter(){
this.typeConverterFactory = new TypeConverterFactory();
this.typeConverterFactory.valueConverter = this;
this.typeConverterFactory.register("array", new ArrayConverter);
this.typeConverterFactory.register("object", new ObjectConverter);
this.dictionary = {};
this.convertToJson = function(valor){
var converter = this.typeConverterFactory.create(type(valor));
converter.dictionary = this.dictionary;
return converter.toJson(valor);
}
this.convertFromJson = function(valor){
var converter = this.typeConverterFactory.create(type(valor));
converter.dictionary = this.dictionary;
return converter.fromJson(valor);
}
}
function JsonRecursive(){
this.valueConverter = new ValueConverter();
}
JsonRecursive.prototype.convert = function(obj){
this.valueConverter.dictionary = [];
var converted = this.valueConverter.convertToJson(obj);
return converted;
}
JsonRecursive.prototype.parse = function(string){
this.valueConverter.dictionary = {};
var referenced = JSON.parse(string);
return this.valueConverter.convertFromJson(referenced);
}
JsonRecursive.prototype.stringify = function(obj){
var converted = this.convert(obj);
var params = [].slice.call(arguments, 1);
return JSON.stringify.apply(JSON, [converted].concat(params));
}
if(window){
if( window.define ){
//to AMD (require.js)
window.define(function(){
return new JsonRecursive();
});
}else{
//basic exposition
window.jsonRecursive = new JsonRecursive();
}
return;
}
if(global){
// export to node.js
module.exports = new JsonRecursive();
}
}());
Sample:
// a object recursive
// var parent = {};
// var child = {};
// parent.child = child;
// child.parent = parent;
//
//results in this recursive json
var json = '{"$id":"0","name":"Parent","child":{"$id":"1","name":"Child","parent":{"$ref":"0"}}}'
//Parsing a Recursive Json to Object with references
var obj = jsonRecursive.parse(json);
// to see results try console.log( obj );
alert(obj.name);
alert(obj.child.name);

Categories

Resources