How to use a variable as a json atribute? - javascript

Hello im working in a generic function that sends an ajax request according with the selection made:
$('#selectAcao, #selectAno').change(function(){
var sthis = $(this);
var sthisTipo = sthis.attr('rel');
var sthisName = sthis.attr('name');
var params = {
"tipo": sthisTipo,
sthisName : sthis.children('option:selected').val(),
"atualiza" : true
}
$.atualizaSelect(params);
});
All I want is pass a "sthisName" variable as a property in "param":
var params = {
"tipo": sthisTipo,
sthisName : sthis.children('option:selected').val(),
"atualiza" : true
}
how can i do this?

That isn't JSON. JSON is a data serialisation format. What you have is a JavaScript object literal.
There is no way to define a property name using a variable at creation time for a JavaScript object.
You have to create the object first, and then add the property.
var myObject = {};
myObject[string_containing_property_name] = some_value;

Related

How to assign (add) value to a undefined item in a json object

I have a external json file and I parse it in to local object,
Currently I know I can't push value into a object so I want to assign a value to them here is my code:
//I parse my JSON into object and name it data
var data = {
...
}
// I use this object as a database so I don't list it all out
var name = "title";
var content = "hello guys";
data[name] = content;
// I wish after this script the object will have one more item like
// {
// ...
// "title": "hello guys",
// ...
//}
But the vscode's console show the following error when I run the script
TypeError: Cannot set property 'title' of undefined
If you can assign value to undefined object how can you add item in to object.
But if there is any way that can let me assign value to undefined item, I'll be very happy
Here is the full code if you need
var jsonfile = require('jsonfile')
var file = './test.json'
var data = jsonfile.readFileSync(file); //I'm very sure data isn't undefined
//console.log(data);
var name="title";
var content="hello guys";
data.post[name] = content;
jsonfile.writeFileSync(file, tmd, {spaces: 4});
currently data = undefined and you are trying to access a key in undefined that is why you are getting an error, you need to assign an empty object to data if it is undefined. you can do something like this:
var data = data || {};
var name = "title";
var content = "hello guys";
data[name] = content;
Probably data has no key named 'post'.
Try this:
data.post = data.post || {};
data.post[name] = content;
EDIT:
I know this is old, but maybe it will help someone.
Here https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options states that readFileSync returns string not data structure.

Javascript / Jquery - How to set a variable name based on a variable

This has been asked a bunch of times before but I'm not grasping it.
In the following..
var variableName = "hello";
How do I make the variable name 'variableName' based on another variable?
PHP Example
$a = 'hello';
$$a = 'hi'; // same as $hello..
echo $hello; // and $hello outputs 'hi'
I specifically need this variable variable to be used for localstorage so it may be syntax that I'm having a problem with.
What I'm Using It For (you can probbaly skip to This Seems To Work)
I want to generate a unique variable name for storing information in local storage. Variable name will be based on the post id of the wordpress post/page which I retrieve with php.
For example we will say the post id is 3333
I add the letters id to the beginning of each post id
So now I have id3333
var postIdNumber = 'id3333';
Then I get 3 other pieces of information that I want to store into local storage about this post (for simplicity I have shown an example output, not the code to get it)
var postURL = 'website.comm/a-wp-post/';
var postTitle = 'A Wordpress Post';
var postThumb = 'website.comm/images/thumb3333.jpg';
Now I want to store this information into local storage
var lsTest = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('lsTest', JSON.stringify(lsTest));
That works fine. Except that I want to be able to store multiple posts into local storage to retrieve later from a 'my favourite posts' page.
So I need a dynamic variable name.
For post ID 3333 I need the variable currently named lsTest to be named id3333
For post ID 4444 I need the variable currently named lsTest to be named id4444
This seems to work (Though I dont fully comprehend it)
solution modified from https://stackoverflow.com/a/5187652/3377049
var variableVariable = {}
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
jQuery('.test-div').text(variableVariable[vv]); // outputs id3333
While this does not..
var variableVariable = {} // also, should this have a ';' ?
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
var variableVariable[vv] = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('variableVariable[vv]', JSON.stringify(variableVariable[vv]));
In PHP I could maybe do something like this.. (for examples sake i'm mixing php variables into JS)
$uv = 'id3333';
$$uv = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('$$uv', JSON.stringify($$uv));
You just need to create an object of objects, keyed off of the unique post id. But then you need to stringify the object before storing it, and parse it when retrieving it.
function saveObject(key, object) {
object = JSON.stringify(object);
window.localStorage.setItem(key, object);
}
function getSavedObject(key) {
var saved = window.localStorage.getItem(key);
if (saved) {
return JSON.parse(saved);
} else {
return null;
}
}
your object:
var lsTest = {
id3333: {
postUrl: postUrl1,
postTitle: postTitle1,
postThumb: postThumb1,
},
id4444: {
postUrl: postUrl2,
postTitle: postTitle2,
postThumb: postThumb2,
}
}
store it:
saveObject('myUniqueSiteName', lsTest);
retrieve it:
var lsTest = getSavedObject('myUniqueSiteName');
adding a new post:
var lsTest = getSavedObject('myUniqueSiteName');
var postId = 'id555';
lsTest[postId] = {
postUrl: postUrl3,
postTitle: postTitle3,
postThumb: postThumb3,
}
saveObject('myUniqueSiteName', lsTest);
Variable variables are not a good idea even in PHP. Just make an array or a hash (which is an object, but it's used as a hash or map, where you can add and delete properties or entries as you please).
var posts = {};
var someId = 3333; //or '3333' if it isn't a number
posts[someId] = {
URL: postURL,
title: postTitle,
thumb: postThumb
};
localStorage.setItem('post' + someId, JSON.stringify(posts[someId]));
A property named "foo" on an object named "bar" can be accessed like so:
bar.foo = 'baz';
console.log(bar.foo);
or like so:
bar['foo'] = 'baz';
console.log(bar['foo']);
Which is the same as:
var name = 'foo';
bar[name] = 'baz';
console.log(bar[name]);
Finally, the global object in JavaScript (which in the browser is window) "holds" the global variables.
var myGlobal = 10;
console.log(window.myGlobal); // logs 10
var globalName = 'foo';
window[globalName] = 'baz';
console.log(foo); //logs 'baz'
Using global variables in general is discouraged. Using them to store posts where the name of the var is the id is highly unorthodox and many JS developers would consider it simply wrong.

How to access property of json object from restful web service

I need to access the name property of the user object that is returned by a restful web service, so far I can see the object being returned, but I do not know how to access the name property and assign it to a variable
User.get.then(function (payload) {
var usrname = '';
var usrobj = angular.fromJson(payload.data);
});
Can someone please show me how can I assign the property name value, to the variable usrname?
Thank you.
is the name attribute in the first level of the object? if yes:
User.get.then(function (payload) {
var usrname;
var usrobj = angular.fromJson(payload.data);
usrname = usrobj.name;
});

Cloud Code add attribute to response

I need to modify / add an attribute to a Parse object before returning it, but not save it to the database.
Here's my scenario:
I do a query for a single record and when successful, I need to add a field to that object:
...
query.first({
success: function(result) {
// get current and expiration date and calculate expiration
var now = new Date();
var expiresInHours = moment(results.get("expiresAt")).diff(now, 'hours');
// set attribute
result.add("expiration", expiresInHours);
// respond to client
response.success(result);
The problem is that I always get an error, because I modified an object and didn't save it.
I would really like to return just the object instead of having to create a new object like
var answer = {"data": result, "expiration": expiresInHours};
which would work, but then I would need to change a lot of code on the client side....
Any help? Thx,
Martin.
On using the "set" method for the object, it will try to save the object where that particular column will not be there so try converting the result to a JSON and try inserting attr to the objects.
var resultsJson = [];
for (var i = 0; i<results.length; i++) {
var resultJson = (results[i].toJSON());
if (relations[results[i].get("user").id] != null) {
resultJson["relationship"] = someValue;
}
resultsJson.push(resultJson);
}
response.success(resultsJson);`

Reading unlabelled JSON arrays

I am trying to pull data, using JQuery, out of an unlabelled array of unlabelled objects (each containing 4 types of data) from a JSON api feed. I want to pull data from the first or second object only. The source of my data is Vircurex crypto-currency exchange.
https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC
By 'unlabelled' I mean of this format (objects without names):
[{"date":1392775971,"tid":1491604,"amount":"0.00710742","price":"40.0534"},{ .... }]
My Javascript look like this:
var turl = 'https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC';
$.getJSON(turl, function (data) {
$.each(data, function(key,obj) {
var ticker1tid = obj[1].tid;
var ticker1amount = obj[1].amount;
var ticker1date = obj[1].date;
var ticker1price = obj[1].price;
});
});
Somehow I am not calling in any data using this. Here is link to my sand-box in JSFiddle: http://jsfiddle.net/s85ER/2/
If you just need the second element in the array, remove the traversing and access it directly from the data:
var turl = 'https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC';
$.getJSON(turl, function (data) {
var ticker1tid = data[1].tid;
var ticker1amount = data[1].amount;
var ticker1date = data[1].date;
var ticker1price = data[1].price;
// Or isn't it better to just have this object?
var ticker = data[1];
ticker.tid // 1491736
ticker.amount // 0.01536367
// etc
});

Categories

Resources