How Can I make this javascript code cleaner? Reuse variables - javascript

I am fairly new to Javascript.I have to count some values and my current vairable looks like this :
var mainObj : {
"main1":{
"var1":0,
"var2":0,
"var3":0
},
"main2":{
"var1":0,
"var2":0,
"var3":0
},
"main3":{
"var1":0,
"var2":0,
"var3":0
}
}
Is there a way i can reuse a single object for all that?
Something like :
var mainObj :{
"main1":{
someOBjInstance
},
,
"main2":{
someOBjInstance
} "main3":{
someOBjInstance
}
}

It is just a matter of creating copies of the object:
var subObject = {
"var1":0,
"var2":0,
"var3":0
};
var mainObj = {
"main1": subObject,
"main2": Object.create(subObject),
"main3": Object.create(subObject)
};
If the values are just a bunch of numbers which you want to increment, then you could use arrays instead of Object, which will be faster and easier to manipulate:
var mainArray = [[0,0,0],[0,0,0],[0,0,0]]

Related

Naming a JSON array using Jquery

I have an array of JSON:
[{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}]
I want it to be:
{
gitdList: [
{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225? v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},
{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}
]
}
I searched and am finding solutions regarding php only , to use json.encode.
How do I do it using JQUERY?
Have you try like this way? just create an empty object like this object = {} and assign your existing value i.e avatar_urls to it with your desired key i.e gitdList. Hope this will work for you.
var avatar_urls = [{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}]
var object = {};
object.gitdList = avatar_urls;
console.log(object);
Edit: pretty neat and better way to do it.
var object = { gitdList: avatar_urls};
console.log(object);
maybe like this:
var data=[{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}];
var new_data={ 'gitdList': data };
console.log(new_data);

Array push behavior

Although I have some basic JavaScript background, I stumbled upon this code that I wrote:
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}]
var tempArr=[];
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
console.log('table'+JSON.stringify(table));
});
In the final loop, I expected table to contain the arrays for Tom, Pat, and Sam . Instead, this is what I got:
table[["Tom","Moody","Tom#example.com",30]]
table[["Pat","Smith","pat#example.com",32],["Pat","Smith","pat#example.com",32]]
table[["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28]]
table[["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28]]
Why is push() replacing the previous entry in table? Any help will be highly appreciated.
The others already pointed out problems in your code.
However, you also make things more complicated than necessary. You can just do this:
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}];
var table = data.map(function(user) {
return [
user.fName,
user.lName,
user.email,
user.age,
];
});
console.log(table);
Or if you use ES6:
var table = data.map(user => [ user.fName, user.lName, user.email, user.age ];
You don't need to write all the boilerplate code by hand. Use a proper array iterator (map in your case).
var table = data.map(function(user) {
return [user.fName, user.lName, user.email, user.age];
});
Obviously map isthe way to go for the sake of functional approach however if you like imperative styles one simplistic way could be using for of loop as follows.
var data = [{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}],
table = [];
for (var user of data) table.push([user.fName,user.lName,user.email,user.age]);
console.log(table);
Problem here is not with push. Variable in javascript store reference to array. And in table you are pushing reference to same array tempArr. You need to create new array before pushing it or create deep copy of array before pushing it.
Example
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}]
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
var tempArr=[];
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
console.log('table'+JSON.stringify(table));
});
Well, unlike a lot of other languages, JavaScript has passes everything by reference. That means that when you table.push(tempArr);, you're not actually pushing the values of tempArr, you're pushing a reference to tempArr. So, if you do this:
var a = 'a';
var table = [];
table.push(a);
a = 'b';
console.log(table[0]);
You'll get b as your output. What you want to do is define a new variable to push, like this
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}]
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
var tempArr=[];
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
});
console.log('table'+JSON.stringify(table));
var data = [{"_id": "57b3e7ec9b209674f1459f36","fName": "Tom","lName": "Moody","email": "Tom#example.com","age": 30}, {"_id": "57b3e8079b209674f1459f37","fName": "Pat","lName": "Smith","email": "pat#example.com","age": 32}, {"_id": "57b3e8209b209674f1459f38","fName": "Sam","lName": "Dawn","email": "sam#example.com","age": 28}, {"_id": "57b3e8219b209674f1459f39","fName": "Sam","lName": "Dawn","email": "sam#example.com","age": 28}],
table = [];
data.forEach(function(user) {
table.push([user.fName, user.lName, user.email, user.age]);
});
console.log(table);

How to bind two object to one in JS

I have a query filter in my code, I want to pass these two queries as one like this:
case1
con = {'eq':['case1':dosome]}
case2
con = {'eq':['case1':dosome]}
I need to bind these two at the end like this
{'eq':['case1':dosome],'eq':['case2':dosome]}
the key eq should remain same.
Why not use an object with two properties like
{ eq: { case1: dosome, case2: dosome } }
Sounds like you want an array of objects:
var your_array = new Array();
var con1 = {'eq':{'case1':dosome}}
your_array.push(con1)
var con2 = {'eq':{'case2':dosome}}
your_array.push(con2)
You can then use the methods for accessing parts of the array -> http://www.w3schools.com/js/js_array_methods.asp
Use merge() function. Also this will give error: ['case1':dosome]. Try this
<script>
var obj1 = {'eq':{'case1':dosome}};
var obj2 = {'eq':{'case2':dosome}}
var merge = obj1.merge(obj2);
</script>
Hope this helps
You can try this:
{ eq: [
{ condition: 'case1', action: doSome } ,
{ condition: 'case2', action : doSomeOther }
]}

Add [DataObject] to exsisting array with var key

Using Cordova, I am trying to get an Object to add to an array. I have this working on node JS using :
theData = {[varkey]:DataObject};
But I can't get this to work the same way within my javascript that cordova runs.
I need to do the following:
var TownName = 'Auckland', var townData = (JSON Data);
theArray = new Array();
theArray[TownName] = townData;
I need to be able to call it back as:
theArray['Auckland']
Which will return (JSON Data)
But it doesn't want to store the data with the key inside the array.
I have also tried:
theArray.TownName = townData;
theArray = [{TownName:townData}];
theArray = {[TownName]:townData}];
Nothing wants to store the data.
Any suggestions?
::EDIT::
data.theData =
"Auckland"[
{
"username":"pndemoname1",
"number":"373456",
"www":"http://373456.pndemoname1",
"icon":"/imgs/pndemoname1.png"
},
{
"username":"pndemoname2",
"number":"373458",
"www":"http://373458.pndemoname2",
"icon":"/imgs/pndemoname2.png"
}
data.town = "Auckland";
townData = new Array();
alert(JSON.stringify(data.theData))//Alerts theData
townData[data.town] = data.theData
alert(townData[townName]) //Alerts undefined
::EDIT2::
Re-defining the array within the function that deals with all of the data, seems to make it work.
As per my answer, the issue was that I assumed javascript vars are global.
Use objects or an array of objects.
A data structure like this:
{
town1: town1Data,
town2: town2Data,
}
Or more common:
[
{
name: "Town 1",
data: {...}
},
{
name: "Town 2",
data: {...}
},
]
For reference:
http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/
I got what you're trying to do, to add property names dynamically to your object is first, by making sure you are using an OBJECT instead of an array, so when you want to store something you will do the following:
var _obj = {}, _something = 'xyz';
_obj[ _something ] = { ... }; // json structure
The problem you're facing is that you want to assign a string value as a key inside your array, which will not work.
However, you can still use the array you defined and do the following:
var _array = new array();
_array.push( { .... } ); // insert json structure
Remember! By using the array you will have to loop through all values every time you want to access your key, just as the best practice to avoid getting into errors.
Good luck.
The issue was that I didn't define the array within the function of where I was trying to add the information to.
I assumed the var was global (Too much PHP)

Accessing a javascript object in D3.js

A javascript data object (JSON notation) has been created with the following content:
"[
{"range":"Shape","values":[{"idx":0,"val":"Random"},{"idx":1,"val":"Line"},{"idx":2,"val":"Square"},{"idx":3,"val":"Circle"},{"idx":4,"val":"Oval"},{"idx":5,"val":"Egg"}]},
{"range":"Color","values":[{"idx":0,"val":"Red"},{"idx":1,"val":"Blue"},{"idx":2,"val":"Yellow"},{"idx":3,"val":"Green"},{"idx":4,"val":"Cyan"}]}
]"
In a next step the index of an ordinal value has to be found in this object. The function should find the index of the value 'Blue' in the range 'Color'.
So the function should have the meta scripting form
f("Color")("Blue")=1
What is the most elegant form to create such a function in the context of D3 and javascript?
Depending on your use case, it might make sense to convert the data structure to a different structure more suitable for direct access. E.g. you could convert your structure to
var data = {
Shape: ['Random', 'Line', ...],
// ...
};
and access it with
data['Shape'].indexOf('Line') // or data.Shape.indexOf('Line')
Or go even one step further and convert to
var data = {
Shape: {
Random: 0,
Line: 1,
// ...
},
// ...
};
and access it with
data['Shape']['Line'] // or data.Shape.Line
What the best solution is depends on the actual use case.
Converting the structure dynamically is pretty straight forward. Here is an example to convert it to the first suggestion:
var newData = {};
data.forEach(function(item) {
newData[item.range] =
item.values.map(function(value) { return value.val; });
});
This would also reduce redundancy (e.g. idx seems to correspond with the element index).
Would this work for you ?
var dataJson = '[ \
{"range":"Shape","values":[{"idx":0,"val":"Random"},{"idx":1,"val":"Line"},{"idx":2,"val":"Square"},{"idx":3,"val":"Circle"},{"idx":4,"val":"Oval"},{"idx":5,"val":"Egg"}]},\
{"range":"Color","values":[{"idx":0,"val":"Red"},{"idx":1,"val":"Blue"},{"idx":2,"val":"Yellow"},{"idx":3,"val":"Green"},{"idx":4,"val":"Cyan"}]}\
]';
var data = JSON.parse(dataJson);
for (each in data){
if ( (data[each].range) === 'Color'){
for (eachVal in data[each].values){
if (data[each].values[eachVal].val === 'Blue'){
alert(data[each].values[eachVal].idx);
}
}
} ;
}
And here is the JSFiddle for you too.

Categories

Resources