Adding keys to objects in a parse object - javascript

Im working with the parse javascript sdk and i want to add a key to an object in a Parse 'object' when saving it.
For ex:
var saveGif = new SaveGifTags();
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: newGif
}, {
success: function(data) {
console.log(data);
res.json(data);
},
error: function(data) {
console.log(data);
}
});
gifObjects is my object in the Parse Class. I tried to do something like this
gifObjects: gifOjects[gifObj.id] = newGif;
newGif of course is the object i want to save. This gave me an error of gifObjects is not defined. So i tried something like this
gifObjects[gifObj.id] : newGif;
that didnt work either. i want to create something like this:
{
hgs32: {
url: '',
image: ''
},
64522 : {
url: '',
image: ''
}
}
any suggestions?

Figured it out. Not sure what the downvote is for, but i had to create the object before i saved it.
var gifObjects = {};
gifObjects[gifObj.id] = newGif;
and then the save
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: gifObjects
},

Related

How to structure a JSON call

I have an endpoint which I call with Axios and the response looks like (for example):
items: [
{
url: "https://api.example1...",
expirationDate: "2019-11-15T00:00:00+01:00"
},
{
url: "https://api.example2...",
expirationDate: "2019-12-20T00:00:00+01:00"
},
{
url: "https://api.example3...",
expirationDate: "2020-01-17T00:00:00+01:00"
},
...and so on.
If I go to one of the url:s in the browser the structure of the JSON is:
fooBar: {
url: "https://api.foo...",
id: "123",
type: "INDEX",
source: "Foobar",
quotes: {
url: "https://api.bar..."
}
},
I need to get the quotes of the two first url:s in items:[] dynamically because they will disappear when the 'expirationDate' is older than today's date.
How can this be achieved? Thanks in advance!
If I understand the requirements correctly you need to:
get the list of items
get item details for first two items (to extract links to quotes)
get quotes for first two items
You can use promise chaining to execute these operations maintaining the order:
const getQuotes = (item) => axios.get(item.url)
.then(resp => axios.get(resp.data.fooBar.quotes.url));
axios.get('/items') // here should be the url that you use to get items array
.then(resp => resp.data.slice(0, 2).map(getQuotes))
.then(quotes => Promise.all(quotes))
.then(quotes => {
console.log(quotes);
});
Please find my proposal below. I gave two examples. You can get the whole quotes object, or just the URL inside the quotes object.
This is just a console log, but you can easily ie. append this data to a div in the html or pass this URL to some other function.
$(function() {
const address = 'https://api.example1...';
function loadQuotes() {
$.ajax({
url: address,
dataType: 'json',
}).done(function(response) {
response.forEach(el => {
console.log(`el.quotes`);
// or if you want to be more specific console.log(`el.quotes.url`);
});
});
}
loadQuotes();
});
If these are nested objects, just append fooBar.
For example change the .done part to:
.done(function(response) {
let qqq = response.quotes
quotes.forEach(el => {
console.log(`el.quotes`);
// or if you want to be more specific console.log(`el.quotes.url`);
});

pass array of numbers from ajax to controller

I know this is a popular topic and I've tried all of the solutions I could find already out there to no avail. I've used all the solutions included for this questions: Pass a List from javascript to controller. I've simplified my test to ridiculously simple. I get into the controller but my controller input param is {int[0]}. I confirmed my array data looks good in the JavaScript and ajax call.
Can anyone please tell me what I am missing?
JavaScript Code
var selectedIds = [];
selectedIds.push(565);
selectedIds.push(573);
selectedIds.push(571);
// selectedIds = [565, 573, 571]
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
data: { "ids": JSON.stringify(selectedIds) },
//data: { "ids": selectedIds},
//data: { ids: selectedIds},
url: "api/services/getbuildingsbyid",
success: function (result) {
return result;
}
});
Controller Code
[HttpPost]
public bool GetBuildingsById(int[] ids)
{
var lookAtIds = ids; // {int[0]}
return true;
}
By using JSON.stringify(selectedIds) you are turning an array of int into a string representation of said array.
The AJAX POST ends up like so:
{ "ids": "[565, 573, 571]" }
instead of
{ "ids": [565, 573, 571] }
If instead you just use the variable for the data, that should resolve the issue:
data: { "ids": selectedIds },
Edit-
Working backwards, by setting a variable to the data we can see the following:
var data = {"ids": JSON.stringify(selectedIds)}
typeof(data["ids"]) // string
data["ids"][0] // '['
data = {"ids": selectedIds}
typeof(data["ids"]) // object
data["ids"][0] // 565
I use:
public ActionResult GetBuildingsById(String selectedIds)
{
// this line convert the json to a list of your type, exactly what you want.
IList<int> Ids = new JavaScriptSerializer().Deserialize<IList<int>>(selectedIds);
return Content(ids[0].ToString());
}
This will take you selectedIds = [565, 573, 571]
and create the list of your type List

Setting up a Todo List server

I'm fairly new to Javascript, Node.js and JSON. I'm supposed to build some sort of Todo list application, where the user sends his todo to a server. I've already created the HTML and Javascript to execute the basic operation without the server.
I'm using the following program/languages in order to complete my assignment:
Vagrant (various NPM modules)
VirtualBox
Javascript (jQuery)
Currently i'm trying to send the data via the following lines of code:
//Create (simplified) "task"
item["id"] = task.dataset.id;
item["taskname"] = task.dataset.taskname;
item = JSON.stringify(item);
//Send code
$.ajax({
url: '/addtodo',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: item
});
Where as on the receiving side, I try to receive the data using the following lines of code:
app.post("/addtodo", function (req, res) {
var newTodo = req.body;
fs.writeFile("Somefile.json", JSON.parse(newTodo), function(err) {
if(err) {
res.json({"message":"Storing data failed"});
} else {
res.json({"message":"Data stored successfully"});
}
});
});
My objective is to get something like this in "Somefile.json"
[{
"id" : 2,
"taskname" : "Example task 2",
},
{
"id" : 2,
"taskname" : "Example task 2",
},
]
For now I get either errors or it changes the Somefile.json into [object Object].
Anyone care to explain what I did wrong and how I should fix it
Edit:
If I do not use JSON.parse i get : [object Object]
If I use JSON.stringify I get {"{\"id\":\"6\",\"taskname\":\"1234\"}":""}
Instead of the
JSON.parse(newToDo);
Use
JSON.stringify(newToDo);
This function will convert the object into a string and will give you the desired output.

Need help parsing jquery datatables editor data

I have a data format that I receive from jquery data tables editor Datatables Editor which looks like the one below and I need to parse it so that I can store it into db but I have not figured out a way of doing so.
{ action: 'edit',
'data[1][Name]': 'Some Text ',
'data[1][Rating]': '1',
'data[1][Division]': 'Some Text '
}
What is the best way to parse this form of data using javascript ? The editor library comes with a php library for parsing the data but I am using nodejs for the backend/
If you want to convert data[] into a literal, you could do something like this :
var prop, fieldName, literal = {};
for (prop in data) {
if (prop != 'action') {
fieldName = prop.match(/\[(.*?)\]/g)[1].replace(/\]|\[/g,'');
literal[fieldName] = data[prop];
}
}
→demo. It will produce a literal like
{Name: "Some Text ", Rating: "1", Division: "Some Text "}
that can be used to be inserted in a mongodb for example.
It simply loops through data, extracts each #2 [] and take the content of that bracket as property names to the literal. I do not at all claim this is the best method.
I have new and maybe a bit more systematic approach, that excludes risc of '[]' characters in regexed strings. Very simple way is to use custom ajax, I have used my own data:
const editor = new $.fn.dataTable.Editor({
ajax: (method, url, data, success, error) => {
$.ajax({
type: 'POST',
url: '/updateproductcode',
data: JSON.stringify(data),
success: (json) => {
success(json);
},
error: (xhr, error, thrown) => {
error(xhr, error, thrown);
}
});
},
table: '#mytable',
idSrc: 'productcode',
fields: ...
Then on serverside you receive object, whose key is your stringified data:
{'{"action":"edit","data":{"08588001339265":{"productcode":"08588001339265","name":"does_not_existasdfadsf","pdkname":"Prokain Penicilin G 1.5 Biotika ims.inj.s.10x1.5MU","suklcode":"0201964","pdkcode":"2895002"}
}:''}
If you parse the key of it with JSON.parse(Object.keys(req.body)[0]), you get your results:
{ action: 'edit',
data:
{ '08588001339265':
{ productcode: '08588001339265',
name: 'does_not_existasdfadsf',
pdkname: 'Prokain Penicilin G 1.5 Biotika ims.inj.s.10x1.5MU',
suklcode: '0201964',
pdkcode: '2895002' } } }

Add elements in the DOM with JS

I'm trying to print in the HTML the data from another part of the site, the data appears on the console, however not in the HTML.
I believe it is an error in the code, could someone point me or direct me?
$.ajax({
type: "GET",
url: 'https://example.com',
crossDomain: true,
success: function (json) {
var reservas = json;
reservas.forEach(function (reserva) {
$(".reservas").append($("<td/>", {
html: reserva
}));
console.log(reserva);
});
},
error: function (e) {
console.log(e);
}
});
If i change the variable reservas for:
var reservas = ["test", "test2", "test3"]
And the elements are being added..
when I give console.log (reserve), the console return:
Object {
_id: "10152686662737642",
nome: "First Person",
email: "email1#gmail.com",
__v: 0
}(index):68
Object {
_id: "10152433045473800",
nome: "Second Person",
email: "email2#gmail.com",
__v: 0
} (index):68
maybe the problem is that is not an array?
Based on your clarifications. I believe what you want to do is:
$(".reservas").append($("<td/>", {
html: JSON.stringify(reserva)
}));
either that or $(".reservas") isn't finding any elements in the DOM. Also you may want to do something like:
$(".reservas").append($("<td/>", {
html: reserva.nome + " " + reserva.email
}));
instead depending on what you actually want to display

Categories