Using variables as keys in multidimensional object - javascript

If I have some values and I want to store it as an object. So finally I need to call JSON.stringify() (because I am trying to store it in chrome extension)
var id = '1';
var name = 'Mali Bakery'
var url = 'http://example.com/'
So I thought the best thing would be sorting it like:
var items = {
id : {
'name': name,
'url': url
}
}
But I couldn't figure out how to put the variables inside the object template.
I tried using
item = {}
item[id] = id
item[id].name = name
// etc
items.push(item);
// and also, this approach too
items.id = id
But no success.

You can put id in brackets [] so that it gets evaluated to the variables value:
var id = '1';
var name = 'Mali Bakery'
var url = 'http://example.com/'
var items = {
[id] : {
name,
url
}
}
console.log(items);
Note that you shouldn't use name as a variable's name!

You could do this
var id = '1';
var name = 'Mali Bakery'
var url = 'http://example.com/'
var items = {}
items[id] = {
'name': name,
'url': url
}
console.log(items);
This gives the following output:
{
1:{
name: "Mali Bakery",
url: "http://example.com/"
}
}

var items = {};
items[id] = { name, url };

var id = '1';
var name = 'Mali Bakery'
var url = 'http://example.com/'
var obj = {
'name': name,
'url': url
}
var items = {};
items[id] = obj;

Related

why my array is undefined in my savetime function but running properly in other functions?

i m calling my save function and st_bookmark and ed_bookmark array donot show any data in my JSON stringfy function the array is undefined or uncaught type error occur
<script>
var check = true;
var st_bookmark = new Array();
var str_print = new Array();
var end_print = new Array();
var ed_bookmark = new Array();
</script>
<script>
function save() {
var link = "M7lc1UVf-VE";
var bk_name = $('#bookmark_name').val();
var bk_tags = $('#bookmark_tags').val();
var bk_email = $('#bookmark_email').val();
var user = '#Session["email"]';
var t = st_bookmark.pop();
var ss = ed_bookmark.pop();
var data =
({ name: bk_name, tags: bk_tags, email: bk_email, link: link, start_bookmark: st_bookmark, end_bookmark: ed_bookmark });
$.ajax({
url: '#Url.Action("save_bookmark", "chopaal")',
type: "POST",
contentType: "application/json",
data: { data: data },
success: function () {
window.alert('success!!');
}
});
var check = true;
var st_bookmark = [];
var str_print = [];
var end_print = [];
var ed_bookmark = [];
}
function starttime() {
if (check == true) {
temp = player.getCurrentTime();
st_bookmark.push(temp);
str_print.push((temp / 60).toFixed(2));
document.getElementById("str_book").innerHTML = str_print;
check = false;
} else {
window.alert("Please End The Previous Bookmark");
}
}
function endtime() {
if (check == false) {
temp = player.getCurrentTime();
ed_bookmark.push(temp);
end_print.push((temp / 60).toFixed(2));
document.getElementById("end_book").innerHTML = end_print;
check = true;
} else {
window.alert("Please Add the Starting Bookmark");
}
}
</script>
Variable declarations are hoisted in JavaScript:
var data = {start_bookmark: st_bookmark};
var st_bookmark = [];
is equivalent to
var data;
var st_bookmark;
data = {start_bookmark: st_bookmark};
st_bookmark = [];
As you can see, st_bookmark is accessed before it got a value assignment, at which point its value is still undefined.
I guess what you really want is to access the variables with the same name that are declared globally. In that case, you should completely remove the declarations of these similarly named variables from save.
If you want to "reset" those variables after the Ajax call was successful, you need to move the assignment inside the success callback and remove the var keyword (so that the identifiers refer to the global variables):
success: function() {
window.alert('success!!');
check = true;
st_bookmark = [];
str_print = [];
end_print = [];
ed_bookmark = [];
}

Javascript split url on filters

Im giving my users the possibility to filter products without refreshing the page with ajax. i update the url to make it look like :
http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4
where the int values are id's split by -.
so i have the options:
style
price
brand
color
what i want is get these values in a var for each filter option so that i end with :
var styleValues = 7,1,2
var priceValues = 4,5,7
if only price filter is selected the url will look like
http://mywebsite.com/products/filter?price=4-5-7
so i cant split on the tags for the filters.
I really like to know what would be the best way to turn the url to different vars.
What i already know :
how to get the filter part:
var filterPart =window.location.search;
Great article on css tricks covering just this:
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
JavaScript can access the current URL in parts. For this URL:
http://css-tricks.com/example/index.html
window.location.protocol = "http:"
window.location.host = "css-tricks.com"
window.location.pathname = "example/index.html"
So to get the full URL path in JavaScript:
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
If you need to breath up the pathname, for example a URL like http://css-tricks.com/blah/blah/blah/index.html, you can split the string on "/" characters
var pathArray = window.location.pathname.split( '/' );
Then access the different parts by the parts of the array, like
var secondLevelLocation = pathArray[0];
To put that pathname back together, you can stitch together the array and put the "/"'s back in:
var newPathname = "";
for (i = 0; i < pathArray.length; i++) {
newPathname += "/";
newPathname += pathArray[i];
}
Or like this::
http://css-tricks.com/snippets/javascript/get-url-variables/
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
maybe this can help you :
var Request = {
QueryString : function (item) {
var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i"));
return svalue?svalue[1]:svalue;
},
queryAllString : function() {
var urlLocation = location.href;
var startPosition = urlLocation.indexOf("?");
if (startPosition < 0) {
return '';
} else {
return urlLocation.slice(startPosition);
}
}
}
If you want to get price,you can do like this:
Request.QueryString("price")
My own take on this problem would be:
// this is simply to compensate for the lack of a current document.location to search:
var documentURL = 'http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4',
tempA = document.createElement('a');
tempA.href = documentURL
var searches = {
'get': function() {
var queries = {
// a cache of all named parameters found:
'found': []
},
// stripping off the leading '?':
queryString = tempA.search.substring(1),
// getting the key-value pairs:
keyValues = queryString.split('&'),
// to be used withi the forEach():
pair;
keyValues.forEach(function(el) {
// creating an array consisting of the keyName and keyValue:
pair = el.split('=');
// if we have both a name and a value we proceed:
if (pair.length === 2) {
if (!queries[pair[0]]) {
// if there is no present entry for the current key, we:
// push the key to the 'found' array, and
// create a record in the queries object for that key
// containing an array of the found values:
queries.found.push(pair[0]);
queries[pair[0]] = pair[1].split('-');
} else {
// otherwise (there is an existing key in the queries object),
// we push the values to the end of the existing array:
queries[pair[0]].push(pair[1])
}
}
});
return queries;
}
};
var cachedSearches = searches.get(),
allKeys = cachedSearches.found;
allKeys.forEach(function(el){
console.log(el, cachedSearches[el], cachedSearches[el].join(', '));
});
References:
Array.prototype.forEach().
Array.prototype.join().
String.prototype.split().
Try
var filtered = {};
var url = "http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4";
var filters = url.split("?")[1].split("&");
filters.map(function(val) {
filtered[val.split("=")[0]] = val.split("=")[1].split("-").join(",")
});
console.log(filtered);
var filtered = {};
var url = "http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4";
var filters = url.split("?")[1].split("&");
filters.map(function(val, i) {
filtered[val.split("=")[0]] = val.split("=")[1].split("-").join(",");
document.body.innerText += (Object.keys(filtered)[i].toString() +": "+ filtered[val.split("=")[0]]) + "\n"
});

combining multiple arrays into an object with first array items as the key

I have these following arrays
var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1','platform-a2','platform-a3'];
var platform_b = ['platform-b1','platform-b2','platform-b3'];
var platform_c = ['platform-c1','platform-c2','platform-c3'];
And I want to convert them into a json which should look like this
{
"Guitar":["platform-a1","platform-a2","platform-a3"],
"Bass":["platform-b1","platform-b2","platform-b3"],
"Amp":["platform-c1","platform-c2","platform-c3"]
}
How would I do this? I would have to do this in pure javascript
Let's present three different approaches to your case:
First one
If you want just to create the json object with your data try:
http://jsfiddle.net/csdtesting/tap2xom9/
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var category = ['Guitar', 'Bass', 'Amps'];
var obj = {
Guitar: platform_a,
Bass: platform_b,
Amps: platform_c
};
document.write(JSON.stringify(obj));
Second
If you want to create it dynamically do something like that:
http://jsfiddle.net/csdtesting/tap2xom9/
var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var FinalObject = {};
FinalObject[category[0]] = platform_a;
FinalObject[category[1]] = platform_b;
FinalObject[category[2]] = platform_c;
document.write(JSON.stringify(FinalObject));
Finally
If you want to be more dynamic then try this :
http://jsfiddle.net/csdtesting/kqwz72os/
var FinalObject = {};
var category = ['Guitar', 'Bass', 'Amps'];
var platforms = {
platform_a: ['platform-a1', 'platform-a2', 'platform-a3'],
platform_b: ['platform-b1', 'platform-b2', 'platform-b3'],
platform_c: ['platform-c1', 'platform-c2', 'platform-c3']
};
for (var i = 0; i < category.length; i++) {
FinalObject[category[i]] = platforms[Object.keys(platforms)[i]];
}
document.write(JSON.stringify(FinalObject));
Hope this helps!
There's no reasonable shortcut here. You just have to do it manually:
var jsonString = JSON.stringify({
"Guitar": platform_a,
"Base": platform_b,
"Amp": platform_c
});

Extracting data form another section with same ID (Appcelerator)

I have the following JSON: (its simplified a bit for you)
{ returnJSON = {
studentDataVOs = {
finalGrades = (
{
grade = A;
percent = 100;
sectionid = 7744;
reportingTermId = 801;
},
{
grade = B+;
percent = 89;
sectionid = 7745;
reportingTermID = 801;
});
reportingTerms = (
{
id = 801;
title = S1;
},
{
id = 802;
title = S2;
});
sections = (
{
id = 7744;
termID = 801;
courseTitle = Physics;
courseCode = 88A;
},
{
id = 7745;
termID = 801;
courseTitle = Government;
courseCode = 90B;
});
};
};
}
I am building an app using Appcelerator Titanium that displays a table view with the data hopefully showing the following:
Physics (88A) - S1 (Grade: A, 100%)
Government (90B) - S1 (Grade: B+, 89%)
...and so on...
I have the table view set up and the following code extracts the data from the sections and puts it in the labels of the table view:
var response = JSON.parse(response);
var sections = response.returnJSON.studentDataVOs.sections;
for (i=0;i<sections.length;i++) {
var courseName = sections[i].courseTitle;
var courseCode = sections[i].courseCode;
}
What I cannot figure out is how to go about fetching the grade, and term title for each individual class. As you can see, the data for each section contains an ID and termID, which direct me to a section in the finalGrades and reportingTerms that contains the ID or termID, where I need to fetch the final grades, percents, and term titles.
Can anyone help me with this? I have been trying on and off for two days trying to figure this out...
You should create indexes for each field you've listed. It's pretty simple:
//for example you have user list
var users = [{
id : 1, email : 'user#gmail.com',
nickname : 'John'
}, {
id : 2, email : 'user#stackoverflow.com',
nickname : 'Peter'
}];
//and you need to query user by his email, id and nickname
//first, create 3 index list
var usersIdIndex = {}, usersEmailIndex = {},
usersNicknameIndex = {};
//then fill them
users.forEach(function(user){
usersIdIndex[user.id] = user;
usersEmailIndex[user.email] = user;
usersNicknameIndex[user.nickname] = user;
});
//now you can get users by any of this fields
//for example
console.log(usersIdIndex[2].nickname== 'Peter');
console.log(usersNicknameIndex['John'].email == 'user#gmail.com');
Sections -> Final Grades
In the sections list, I would pass a variable in the tablerow that I could use to query for the next set of data. You need the section id to associate the data with the data in the final grade, so I would add it to my table row.
When creating your table:
// This loop to loop through the data.
function getSections(_args){
var response = JSON.parse(response);
var sections = response.returnJSON.studentDataVOs.sections;
for (i=0;i<sections.length;i++) {
createMyRow({
courseName: sections[i].courseTitle,
courseCode: sections[i].courseCode,
sectionId: sections[i].id
});
}
}
// This function creates the rows for the table
function createMyRow(_args){
// the sectionId is now included in the tableRow and can be used later for your
// next query.
// allows the sectionId value is now can be queried when a user clicks it
// through e.rowData.
var tableRow = Ti.UI.createTableViewRow({
sectionId: _args.sectionId
});
var title = Ti.UI.createLabel({
text: _args.courseName
});
tableRow.add(title);
return tableRow;
}
var tableView = Ti.UI.createTableView();
var data = [];
function refreshTable()
data = getSections();
var rows = [];
for( var i = 0; i<data.length; i++){
rows.push(createMyRow(data[i]);
}
tableView.setData(rows);
}
// this passes the value of the sectionId so you can use it to look up your next section.
tableView.addEventListener('click', function(e){
getFinalGrades({
sectionId: e.rowData.sectionId
})
});
function getFinalGrades(_args){
var finalGrades = response.returnJSON.studentDataVOs.finalGrades
var data = [];
for (i=0;i<finalGrades.length;i++) {
if(finalGrades[i].sectionId == _args.sectionId){
data.push({
grade: finalGrades[i].grade,
percent: finalGrades[i].percent
});
}
}
return data;
}
I hacked this together rather quickly looking at some of my code examples. At the end of the getFinalGrades function, you would have an array of finalGrades that were only from sectionId you clicked.

Javascript | Objects, Arrays and functions

may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);

Categories