i want json array like["ajsa","ajhsahs"] - javascript

function createJSON() {
jsonObj = [];
$("input[class=email]").each(function () {
var id = $(this).attr("title");
var email = $(this).val();
item = {}
item["title"] = id;
item["email"] = email;
jsonObj.push(item);
});
console.log(jsonObj);
}
I tried this but I want json array like ["ajsa","ajhsahs"]. How can achieve this? I tried to do it with key but I don't need key I only need value. The javascript array should should be converted to json array.

what you mean when you say value? use this for array of emails:
function createJSON() {
jsonObj = [];
$("input[class=email]").each(function () {
var email = $(this).val();
jsonObj.push(email);
});
console.log(jsonObj);
//and if you want it in string:
var stringObj = JSON.stringify(jsonObj);
return jsonObj;
}

Related

Using variables as keys in multidimensional object

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;

JSON.parse using reviver function

How to use JSON.parse reviver method to edit a certain value.
I just want to edit every key which is declared as lastname and than return the new value.
var myObj = new Object();
myObj.firstname = "mike";
myObj.lastname = "smith";
var jsonString = JSON.stringify(myObj);
var jsonObj = JSON.parse(jsonString, dataReviver);
function dataReviver(key, value)
{
if(key == 'lastname')
{
var newLastname = "test";
return newLastname;
}
}
After checking for the special case(s), you simply need to pass back unmodified values by default:
var myObj = new Object();
myObj.firstname = "mike";
myObj.lastname = "smith";
var jsonString = JSON.stringify(myObj);
var jsonObj = JSON.parse(jsonString, dataReviver);
function dataReviver(key, value)
{
if(key == 'lastname')
{
var newLastname = "test";
return newLastname;
}
return value; // < here is where un-modified key/value pass though
}
JSON.stringify(jsonObj )// "{"firstname":"mike","lastname":"test"}"

Why ScriptDb query result object is different

function myFunction() {
var item = {};
item = {id:'myId', rules: {1:'rule1', 2:'rule2'}};
Logger.log(item); // {id=myId, rules={2=rule2, 1=rule1}}
Logger.log(item.rules[1]); // rule1
var db = ScriptDb.getMyDb();
db.save(item);
var result = db.query({id:'myId'});
item = result.next();
Logger.log(item); // {id=myId, rules={2=rule2, 1=rule1}}
Logger.log(item.rules[1]); // undefined, why?
}
Expecting the last log to return the value "rule1" like in the original object.
Why is it now undefined?
A strange case, it may be a bug.
With the following code can get what you need:
...
item = JSON.parse(item.toJson());
Logger.log(item); // {id=myId, rules={2=rule2, 1=rule1}}
Logger.log(item.rules[1]); // rule1
...
An alternative route for storing and filtering results with a numerical value instead of with a numerical key.
function myFunction() {
var db = ScriptDb.getMyDb();
var item1 = {id:'myId', rule:{num:1, details:'rule1'}};
var item2 = {id:'myId', rule:{num:2, details:'rule2'}};
var saveResults = db.saveBatch([item1, item2], false);
var results = db.query({id:'myId'});
while (results.hasNext()) {
var item = results.next();
if (item.rule.num == 1)
Logger.log(item.rule.details); // rule1
}
}

Sorting the results of an indexedDB query

I want to sort results obtained from indexedDB.
Each record has structure {id, text, date} where 'id' is the keyPath.
I want to sort the results by date.
My current code is as below:
var trans = db.transaction(['msgs'], IDBTransaction.READ);
var store = trans.objectStore('msgs');
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound("");
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false){
return;
}
console.log(result.value);
result.continue();
};
Actually you have to index the date field in the msgs objectStore and open an index cursor on the objectStore.
var cursorRequest = store.index('date').openCursor(null, 'next'); // or prev
This will get the sorted result. That is how indexes are supposed to be used.
Here's the more efficient way suggested by Josh.
Supposing you created an index on "date":
// Use the literal "readonly" instead of IDBTransaction.READ, which is deprecated:
var trans = db.transaction(['msgs'], "readonly");
var store = trans.objectStore('msgs');
var index = store.index('date');
// Get everything in the store:
var cursorRequest = index.openCursor();
// It's the same as:
// var cursorRequest = index.openCursor(null, "next");
// Or, if you want a "descendent ordering":
// var cursorRequest = index.openCursor(null, "prev");
// Note that there's no need to define a key range if you want all the objects
var res = new Array();
cursorRequest.onsuccess = function(e) {
var cursor = e.target.result;
if (cursor) {
res.push(cursor.value);
cursor.continue();
}
else {
//print res etc....
}
};
More on cursor direction here: http://www.w3.org/TR/IndexedDB/#cursor-concept
IDBIndex API is here: http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex
Thanks to zomg, hughfdjackson of javascript irc, I sorted the final array. Modified code as below:
var trans = db.transaction(['msgs'], IDBTransaction.READ);
var store = trans.objectStore('msgs');
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound("");
var cursorRequest = store.openCursor(keyRange);
var res = new Array();
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false){
**res.sort(function(a,b){return Number(a.date) - Number(b.date);});**
//print res etc....
return;
}
res.push(result.value);
result.continue();
};

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