I have a Customer with Apples, I have an Api Controller that takes an Object Customer as a parameter, and updates the existing one in the database with these new Apples:
[HttpPut("Update")]
public async void Put([FromBody]Customer customer)
{
await _repository.UpdateCustomer(customer);
}
Using Javascript, I want to add these new Apples to my current List of Apples in the Customer. From reading on SO it should look something like:
addApplesToCustomer_method: function () {
var updatedCustomer = this.currentCustomer;
Array.prototype.push.apply(updatedCustomer.apples, this.selectedApples);
$.ajax({
url: 'api/customer/update',
type: 'PUT',
contentType: "application/json",
data: JSON.stringify({
customer: updatedCustomer
}),
success: function () {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + '\n' + errorThrown);
}
});
}
currentCustomer is the customer we want to update. selectedApples is the new List of Apples we want to add to our Customers existing Array of Apples.
The above however does not even run since I added the Array.prototype.push.apply(updatedCustomer.apples, this.selectedApples) but it doesnt give me an error either. Just nothing happens. If I go back to sending the Customer and Apples seperately to my Controller it works, but I don't want to do that.
Use spread syntax.
updatedCustomer.apples.push(...this.selectedApples);
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected, or an object
expression to be expanded in places where zero or more key-value pairs
(for object literals) are expected.
How about just pushing the object onto the array withArray.push(object)
let objectArray = []
let apple = {
name: 'Apple',
size: 'medium'
}
let orange = {
name: 'Orange',
size: 'large'
}
// Create an initial list with apples
for (var i = 0; i < 10; i++) {
objectArray.push(apple)
}
// Now add an orange to that list
objectArray.push(orange)
// The resulting array contains 10 apples, 1 orange.
console.log(objectArray)
Here's the JSFiddle: http://jsfiddle.net/j7kcjjqh/
(Inspect the console to see the result)
Related
I'm new to JSON and jQuery/JavaScript.
How would I pull in a object so that I can use it within jQuery, I've tried 2 attempts
var placements = document.querySelector(placements)
var message = document.querySelector(placements.message)
$.ajax({
type: 'GET',
url: 'https://raw.githubusercontent.com/kieranbs96/developer-exercise/master/data/recommendations.json',
async: false,
dataType: 'json',
success: function (data) {
$("header").append(placements.message);
}
});
Below is the JSON I'm trying to pull in:
{
"placements":[
{
"message":"If you like this, you might be into these",
"items":[
{
"id":"029148",
"name":"Woodblock Play Suit",
"price":"46.00"
},
{
"id":"0294526806",
"name":"Smock Dress",
"price":"39.00"
},
{
"id":"0297180006",
"name":"Cami",
"price":"9.00"
},
{
"id":"0298473606",
"name":"Asymmetric Wrap Cami Dress",
"price":"46.00"
},
{
"id":"0297155306",
"name":"Casual Stripe Tee",
"price":"16.00"
}
]
}
]
}
Marked as duplicate - the other question did not solve my problem - it has been solved by an answer to this question.
You haven't included what the error is or the expected output, but here's two potential errors.
You aren't utilizing the data object returned from your AJAX request.
The value associated with the placements key on your JSON object is an array of objects. Therefore, to access the message key, you'll need to traverse the array.
This is likely what your code should look like:
$("header").append(data.placements[0].message);
First off, you're missing the data object within your append function.
Second, you're missing the key notation of data.placements considering the fact that placements is an array.
You can either use data.placements[0].message to get your preferred data, or, if placements will be extended with more objects in the future, map through your objects like this:
data.placements.map(function(obj, index){
if(index == 0){
$("header").append(obj.message);
}
})
Not necessary if your array will always have a length of 1 of course
This is what I'm doing:
function AddSupervisor()
{
var employeeID = $('#ID').val();
var supervisorId = $('#SupervisorId').val();
var supervisors = '';
if (supervisorId > 0)
{
$.ajax({
url: '#Url.Action("AddSupervisor", "Contact")',
type: 'GET',
dataType: 'json',
data: { EmployeeID: employeeID, SupervisorID: supervisorId },
success: function(data) {
supervisors = data;
$('#divSupervisorList').text(supervisors.replace(",", "<br />"));
},
error: function(data) {
}
});
}
}
This is the error:
Uncaught TypeError: supervisors.replace is not a function
If I do this:
$('#divSupervisorList').text(data);
The the result on screen is this:
John Foo, Jane Bar
What I want is:
John Foo
Jane Bar
But I'm having trouble replacing the , with a <br />. At first I tried:
$('#divSupervisorList').text(data.replace(",", "<br />"));
And when that didn't work, I went to using a string that is declared before the ajax call. I also tried using .split() but got the same error.
Not sure what I'm doing wrong.
UPDATE:
As many have pointed out, my return data is not a string, but an object:
(4) ["Adam Brown", "Karl Walser", "Jeremy Smith", "Nathan Graham"]
0 : "Adam Brown"
1 : "Karl Walser"
2 : "Jeremy Smith"
3 : "Nathan Graham"
So, now I gotta figure out how to split this array into a string :-)
My guess is that the data param is actually an array, not a string, and you're seeing it with commas only because JS is sneakily stringifying it that way. You could combine them in a string using the join method for arrays:
supervisors.join('<br />')
However, if you try to use "<br />" in jQuery's text function, it will get escaped. You can use the html function instead. So,
$('#divSupervisorList').html(supervisors.join('<br />'));
The data you are having in response is a Json and not a string.
function AddSupervisor()
{
var employeeID = $('#ID').val();
var supervisorId = $('#SupervisorId').val();
var supervisors = '';
if (supervisorId > 0)
{
$.ajax({
url: '#Url.Action("AddSupervisor", "Contact")',
type: 'GET',
dataType: 'json',
data: { EmployeeID: employeeID, SupervisorID: supervisorId },
success: function(data) {
supervisors =JSON.stringify( data);
$('#divSupervisorList').text(supervisors.replace(",", "<br />"));
},
error: function(data) {
}
});
}
}
Read more:. [https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify].
To replace commas inside each member of your array, you need to map .replace() on the array values:
let result = data.map(function(o){return o.replace(',','<br />')});
To join the members of the array, separating them with a <br />, you need .join():
let result = data.join('<br />');
Note there are no actual commas separating the array members, that's just a conventional way of displaying array values so humans can read and understand them, but there's nothing to replace. All you need to do is join the members with the separator of your choice (<br />) which, by default, is a comma.
So this would also give you the same result:
let result = data.join().replace(',','<br />');
... because .join() would glue the strings using , and .replace() would replace them with <br />s.
According to the jQuery docs:
[dataType is] "json": Evaluates the response as JSON and returns a JavaScript object
So your data is actually an object. You need to access the relevant string property, e.g. data.supervisors.replace(...) - depending on your object model.
I recommend adding a console.log(data) call to your success callback and checking the developer console in your browser by pressing F12 to investigate the source of your issue.
Update: The output of above call to console.log hints at data being an array. Thus, you need to replace
$('#divSupervisorList').text(data.replace(",", "<br />"));
with
$('#divSupervisorList').html(data.join("<br />"));
I would like to pass a Dictionary> to client using JavaScript.
I did look at this post and I didn't understand exactly how to proceed.
In case I'm doing something wrong I'll explain what I want to do.
The dictionary contains the 'name' key of all worksheets in the Excel file, and the 'value' is the column value of the first row in that worksheet.
The UI of the client should have two "drop list", the first will contain the key which is all the names of the worksheet in the Excel file.
The second contain all the column value of the first row of the worksheets that will choose in the first drop list – which is actually a List as the value in the dictionary.
So all the back end C# code is working fine. Now I need help in the front end JavaScript.
How do I parse the data to a key value so I can do a "search" on the keys as the client chooses some "key" in the first drop list so I can get back the relevant values as a list?
Thanx!
var ajaxRequest = $.ajax({
type: "POST",
url: "http://localhost:1894/api/Values",
contentType: false,
processData: false,
data: data,
success: function(dataTest) {
}
});
This is the JSON that I get back from the server:
{"First":["Name","Link","User","Pass"],"Sec":["test01"]}
How would I perform a search on this like in C#? I want to be able to do something like this: "dict.TryGetValue(key, out value); and the out value would return as an array of string or as a List.
Try this(you don't need var ajaxRequest variable you can directly call like this:
$.ajax({
type: "POST",
url: "http://localhost:1894/api/Values",
dataType: "json",
data: data,
success: function(dataTest) {
//dataTest should contain your data in a javascript object
for(var i = 0; i < dataTest.First.length; i++)
{
window.alert("" + dataTest.First[i]);
}
for(var i = 0; i < dataTest.Sec.length; i++)
{
window.alert("" + dataTest.Sec[i]);
}
//etc...
//this should print the values returned if you showed me exactly how your JSON is...
}
});
The javascript object will contain properties with an array as the value for each property. Think of it like a map of <String, String[]>. So your returned object dataTest will have properties First and Sec and for First the value associated with the key First will be ["Name","Link","User","Pass"] which is just an array. Same for Sec. So `dataTest.First[0] will equal "Name" and dataTest.First[1] will equal "Link" etc...
*****************************************UPDATE**************************************
You can save your dataTest to a global variable in this example (myObject) then you can access like this:
var key = "First";
// Or if you want to get your key from a dropdown (select) element then you could do like this:
var key = document.getElementById("myselect").options[document.getElementById("myselect").selectedIndex].innerHTML;
if(myObject[key] != undefined)
{
//That means there is values for this key.
//Loop through values or do whatever you want with myObject[key].
for(var i = 0; i < myObject[key].length; i++)
{
window.alert("" + myObject[key][i]);
}
}
I have json data that looks like this
{
"projects":{
"COMMERCIAL":[
{
"ppID":"87",
"pTitle":"5th Street Lofts"
},
{
"ppID":"94",
"pTitle":"Skip-a-Long Child Development Services"
}
],
"CORPORATE":[
{
"ppID":"86",
"pTitle":"Caxton Building"
},
{
"ppID":"68",
"pTitle":"Swiss Valley Corporate Headquarters"
}
],
"EDUCATION (COLLEGIATE)":[
{
"ppID":"20",
"pTitle":"Ashford University - Athletic Field"
},
{
"ppID":"64",
"pTitle":"St. Ambrose University - Center For Health And Science Education"
}
]
},
"error":"0"
}
In this example, "COMMERCIAL", "CORPORATE", and "EDUCATION (COLLEGIATE)" are unknown fields names.
I'm getting it from my CGI, which looks like this:
$.ajax({
url: "cgi/myCGI.exe",
dataType: "json",
error: ajaxError,
success: function(json){
if(json.error !== "0"){
alert("error processing request: "+json.error);
return;
}
var temp="";
var i=0;
for(i=0;i<=json.projects.length-1;i++){
// tried something like this
}
$.each(json.projects, function(ppID, pTitle) {
// tried something like this
});
// add to my html
}
});
Ultimately, I want to add HTML to the webpage,
like
<div class="smSubTitle">COMMERCIAL</div>
Fidlar Technologies<br>
Skip-a-Long Child Development Services<br>
<div class="smSubTitle">CORPORATE</div>
etc.
I can't figure out how to get the names of each project "sub title" then it's individual field values.
EDIT:
First, I noticed that json.projects.length is undefined.
I also tried json.projects[0].length but it is also undefined.
in
$.each(json.projects, function(ppID, pTitle) {
console.log("test: "+ppID);
console.log("test: "+pTitle);
});
ppID works, but pTitle says [object,object]
projects property is an object and each object property contains an array. So you have to at first iterate through the object's keys and then the arrays, i.e. 2 nested loops:
var html = '', projects, type, i;
for ( type in json.projects ) {
if ( json.projects.hasOwnProperty(type) ) {
// append the type of the projects
html += "<div class='smSubTitle'>" + type + "</div>";
projects = json.projects[type];
// iterate through each array
for ( i = 0; i < projects.length; i++ ) {
html += "<a href='somePage.html?id="+ projects[i].ppID+ "'>"+ projects[i].pTitle +"</a><br>";
}
}
}
Here is a demo.
I think you have a misunderstanding of what JSON is. JSON is a string and not an object hence it's abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old Javascript Object. They are different.
That said, you can iterate over these objects like so:
Object.keys(json.projects).forEach(function(key, i) {
// key is "COMMERCIAL", "CORPORATE", ...
// You can add the smSubTitle element here
json.projects[key].forEach(function(item) {
// item is an object {ppID: '...', pTitle: '...'}
// You can add a link per object here
});
});
I have found several posts similar to this topic but nothing I have tried has actually worked. My question is simple and should be easy to answer. My return json object will have one key and one value. For my code below, the alert shows "[{"DISCOUNT":1}]" and all I am trying to do is parse out the "1" and display it. Ultimately, I want to plug that value into a variable and use for multiplication, but I can't even get the darn number to display by itself. My code is below:
function codeMatchTest() {
if ($('#dbReturnString').val() == '') {
alert("Please enter a discount code.");
} else {
$.ajax({
type: "POST",
url: "PROMO.svc/MatchCode",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
success: function (json) {
alert(json.d);
/*alert (json.d.discount); // getting "undefined"
$.each(json.d, function (key, value) {
var discount = value;
});
alert("Success: " + discount); //getting "undefined" */
},
error: function () {
alert("There was an error with your request.");
}
});
}
}
I have found no good references on how to actually use the data in a json object. My json object will only consist of a single key and value and I will only ever need to use the value.
Also, I have tried several iteration using $.each and none work. Based on the jquery documentation, it should be very easy but I am having not luck.
If your alert is showing "[{"DISCOUNT":1}]" that means you have an object within an array.
try alert(json.d[0].DISCOUNT);
JSON parsed objects are case sensivetive, plus its seems that json.d contains a string (wich seems to be in json) rather than an object. Try:
var discount = JSON.parse(json.d);
discount = discount[0].DISCOUNT;
success: function(json) {
alert(json.d[0]["DISCOUNT"]);
}
First comment on your code, you are reinventing what jQuery does.
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
It should just be
data: { codeInput: $('#dbReturnString').val().toLowerCase() },
Now to get the data it is simple, you are returning an array with an object in it.
Let us look at it as a regular variable and not an Ajaqx call.
var json = [{"DISCOUNT":1}];
So you got an array? How do you get the object inside of it? You reference the index. Since you said there will only be one index being returned, than use [0] to access it.
success: function (json) {
alert(json[0].DISCOUNT);
To access the first item from the json you may use
alert(json.d[0].DISCOUNT);
Because json.d is an array and it contains one object which is 0 index. So, json.d[0] will select the first item/object from the array and using .DISCOUNT you can access the object's property. It's also possible to access the property like
alert(json.d[0]["DISCOUNT"]);
Try this way
You can use JSON.parse(json.d) / json.d
var data = json.d;
for(i=0;i<data.length;i++) {
alert(data[i].fieldname);
}