Remove items from JSON object dynamically - javascript

I would like to delete certain items from a JSON object under certain conditions.
I am making two Ajax requests, one to get items from an API endpoint and save the JSON object in a variable called items. I'm using the ID of each item to make a subsequent API request.
If the second API returns a non-empty object, delete the specific item from my JSON Object. Then render the items (meaning only display items that are yet to be approved).
API Request 1
var items;
function fetchItems() {
$.ajax({
url: urlOne,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
items = data.d.results;
getPendingItems();
},
});
}
API Request 2
function getPendingItems() {
for (var i = items.length - 1; i >= 0; i--) {
$.ajax({
url: urlTwo + items[i].Id,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
if ($.isEmptyObject(data.d.results)) {
//
} else {
removeItems(i);
}
},
})
}
}
function removeItems(key) {
delete items[key];
}
My Data Structure
[
{
"Id": 1,
"Item_name": "test1"
},
{
"Id": 2,
"Item_name": "test2"
},
{
"Id": 3,
"Item_name": "test3"
},
]
However, the items are not being deleted from my JSON object. I end up rendering all the items

Related

Retrieving data from db.json file and adding it into an array using javascript

I'm using ajax and javascript for a game and I created a server using json-server where I keep a db.json file with words that the user can input and become available in the game.
db.json
This is what the json file looks like
{
"words": [
{
"cuvant": "cuvant",
"id": 1
},
{
"cuvant": "masina",
"id": 2
},
{
"cuvant": "oaie",
"id": 3
},
{
"cuvant": "carte",
"id": 4
},
{
"cuvant": "fmi",
"id": 5
},
{
"cuvant": "birou",
"id": 6
},
{
"cuvant": "birou",
"id": 7
},
{
"cuvant": "canapea",
"id": 8
},
{
"cuvant": "pasare",
"id": 9
I managed to get the POST request (adding the words to the db.json) using this:
function addWord() {
var word = document.getElementById("input-name").value;
var info = {
cuvant: word
}
$.ajax({
url:'http://localhost:3000/words',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(info),
succes: function(info) {
console.log(info)
},
error: function(error) {
console.log(error);
}
})
}
This is what I tried for the GET request
But I'm not sure if it's correct.
And I also need a way to get only the value hold by the cuvant key and add it into an array.
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
contentType: "application/json",
succes: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
I think your code is correct. It was just missing the "s" on "success":
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}

Need help creating a work item in tfs 2015 using javascript

When I try to pass my json object for creating a task item and pass the content-type application/json-patch+json as well and the type PATCH i'm getting an erro: The request indicated a "Content-Type of \"\" for method type \"PATCH\" which is not supported. Valid content types for this method are application/json=patch+json. ".
It works fine when I call it in Postman with the same application type and type Patch. I'm trying to create a webpage and get this to call the service when I click a button on the form.
var newJson = '[{"op":"add","path":"/fields/System.Title","value":"JavaScript implementation for Microsoft Account"}]';
var oJson = JSON.stringify(newJson);
//AZURE URL
var url = "https://dev.azure.com/AIZ-GL-dryrun/375977db-f390-4aac-bc4d-808f51360f9a//_apis/wit/workitems/$task?api-version=5.1";
jQuery.support.cors = true;
$.ajax({
url: url,
async: true,
data: oJson,
type:'PATCH',
contentType: "application/json-patch+json;",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic "+btoa(username+':'+password));
},
success: function(data){
var myObject = JSON.stringify(data);
alert("RESULT: "+myObject);
},
error: function(err) {
alert(JSON.stringify(err))}
});
As Daniel pointed out, var url = "https://dev.azure.com/AIZ-GL-dryrun/375977db-f390-4aac-bc4d-808f51360f9a//_apis/wit/workitems/$task?api-version=5.1"
You were trying to use API with version 5.1. As you can see, this version is not supported with Team Foundation Server 2015.
Need to use version 2.x on TFS 2015 and try again. More detail about api version, kindly take a look at this official link-- REST API Versioning
Update, use post instead of patch and try again.
return $.ajax({
url: "https://{account}.visualstudio.com/DefaultCollection/{project}/_apis/wit/workitems/$Bug?api-version=1.0",
type: "POST",
headers: {
"Authorization": "Basic " + btoa("{user}:{password}"),
"X-HTTP-Method-Override": "PATCH",
"Content-Type": "application/json-patch+json; charset=utf-8"
},
dataType: 'json',
cache: false,
data: JSON.stringify(myData),
async: false,
error: function (jqXHR, textStatus, errorThrown) {
//alert(jqXHR.status + ': ' + errorThrown);
},
success: function (data) {
// alert(JSON.stringify(data));
}
});
Another way, you could also use Work item batch api instead:
For example:
http://[collection url]/_apis/wit/$batch?api-version=1.0
Body:
[
{
"method": "PATCH",
"uri": "/ScrumStarain/_apis/wit/workItems/$Product Backlog Item?api-version=1.0",
"headers": {
"Content-Type": "application/json-patch+json"
},
"body": [
{
"op": "add",
"path": "/fields/System.Title",
"value": "apip1"
},
{
"op": "add",
"path": "/id",
"value": "-1"
}
]
},
{
"method": "PATCH",
"uri": "/ScrumStarain/_apis/wit/workItems/$Task?api-version=1.0",
"headers": {
"Content-Type": "application/json-patch+json"
},
"body": [
{
"op": "add",
"path": "/fields/System.Title",
"value": "apip2"
},
{
"op": "add",
"path": "/id",
"value": "-2"
}
]
}
]
More information, you can refer to: Work item batch operations

jQuery Fire a AJAX call from the returned array from a AJAX call and get the resulting array

I am firing an ajaxcall on page load and getting an array back. Now for each element called groupId present in the array, I have to fire another ajaxcall to get the group name and group notes.
Now I need to create a final array that would have the array returned from the first ajaxcall and merged with the corresponding group name and info returned from the second call.
This is the array returned from the first ajaxcall:
[{
"customMessage": "THis is the first message",
"groupIdx": 13
}, {
"customMessage": "This is the second message",
"groupIdx": 14
}]
Which I am getting by doing:
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/pre-visit-instruction/list"/>',
dataType: "json"
}).done(function(data) {
vueInst.preVisitInstructions = data;
});
Now to this I am appending a .each function and calling another ajaxcall.
This is the final code:
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/pre-visit-instruction/list"/>',
dataType: "json"
}).done(function(data) {
vueInst.preVisitInstructions = data;
}).each(dataObj, function(j, data) {
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/group/"/>' + data.groupIdx + '/info',
dataType: "json"
}).
My question is: How do I get the data returned from the .each function and append it to the original object?
$.each() function must be inside of .done() function.
Update: According to the last comment:
You should use Array#filter.
data.data = response2.filter(function(x) {
return x.groupId === data.groupIdx;
});
Something like this:
$(function() {
var vueInst = {
preVisitInstructions: []
};
var result = [];
$.ajax({
type: "GET",
url: "https://gist.githubusercontent.com/dannyjhonston/17455e3ef90fb3cf096d1f051d4331e5/raw/ad51c85e7722a83e7085ad63e26a524b769efe50/firstData.json",
dataType: "json"
}).done(function(response1) {
$.each(response1, function(j, data) {
$.ajax({
type: "GET",
url: "https://gist.githubusercontent.com/dannyjhonston/e610dd23f830b108bc1e24c78f66b3b6/raw/54851535eedd1e94a1a944ddf3d63412e83349f8/secondData.json",
dataType: "json"
}).done(function(response2) {
data.data = response2.filter(function(x) {
return x.groupId === data.groupIdx;
});
result.push(data);
});
vueInst.preVisitInstructions = result;
});
});
$("#btnCheck").on("click", function() {
console.log(JSON.stringify(vueInst.preVisitInstructions));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnCheck">Check data</button>
The result should be:
[{
"customMessage": "THis is the first message",
"groupIdx": 13,
"data": [
]
},
{
"customMessage": "This is the second message",
"groupIdx": 14,
"data": [{
"groupId": 14,
"groupName": "Test 1",
"groupNotes": "THis is a note"
},
{
"groupId": 14,
"groupName": "Test 2",
"groupNotes": "THis is a note"
},
{
"groupId": 14,
"groupName": "Test 3",
"groupNotes": "THis is a note"
}
]
}
]

how to access properties of json string

I have a JSON string coming from my database table but it has empty root element name
{"": [
{"ID":18,"MenuName":"dsadasdasd","IsActive":"InActive"},
{"ID":17,"MenuName":"Karachi","IsActive":"Active"},
{"ID":2,"MenuName":"User Management","IsActive":"Active"},
{"ID":1,"MenuName":"Home","IsActive":"Active"}
]}
I am trying to access this JSON with below jquery ajax call method
function Get_DataTable() {
$.ajax({
url: "GridView_JqueryFunctionality.aspx/CallDataTable_EmptyRootName",
type: "POST",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d) // showing json is fine
var MyData = $.parseJSON(data.d);
for (i = 0; i < Object.keys(MyData).length; i++) {
alert(MyData[i].ID + ' : ' + MyData[i].MenuName);
}
}
});
}
My Webmethod
[WebMethod(true)]
public static string CallDataTable_EmptyRootName(){
List<Category> Categories = new List<Category>();
clsMenu objMenu = new clsMenu();
DataTable dt = new DataTable();
objMenu.GetAllMenu(dt);
if (dt.Rows.Count > 0){
string jsonString = ConversionExtension.DataTabelToJson(dt);
return jsonString.ToString();
}else{
return "";
}
}
it is giving me undefined : undefined... Please help me. I am stuck now
Try this:
function Get_DataTable() {
$.ajax({
url: "GridView_JqueryFunctionality.aspx/CallDataTable_EmptyRootName",
type: "POST",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d) // showing json is fine
var MyData = $.parseJSON(data.d)[""];
for (i = 0; i < MyData.length; i++) {
alert(MyData[i].ID + ' : ' + MyData[i].MenuName);
}
}
});
}
Assuming you have a variable name for your object, you can reference it with an empty string as the key.
var a = {
"": [
{
"ID": 18,
"MenuName": "dsadasdasd",
"IsActive": "InActive"
},
{
"ID": 17,
"MenuName": "Karachi",
"IsActive": "Active"
},
{
"ID": 2,
"MenuName": "User Management",
"IsActive": "Active"
},
{
"ID": 1,
"MenuName": "Home",
"IsActive": "Active"
}
]
}
console.log(a[""]);
Try running the above code notice we can still access the objects elements despite having an empty root name.
You have to access with brackets the no-name property in the root object, and then iterate over the array of items.
success: function(response) {
var data = $.parseJSON(response.d);
var list = data[""];
list.forEach(function(item, i) {
console.log(item);
console.log(item.ID, ' -> ', item.MenuName);
});
}

How to convert id's in array of objects to a list JavaScript

I am trying to get all IDs from an array objects and put the in a list so they can be passed to a method (API)
var tempObj= Getlist();
var tmpList = tempObj.listOfdata.filter(function (result) { return (result.Id) });
var data = tmpList
then I have my AJAX call
$.ajax({
url: url,
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
async: true,
method: 'POST',
success: function (data) {
console.log(data);
}
});
no data is being passed
If you want to extract values from a collection of objects, don't use filter. Use map.
let list = [
{ id: 1 },
{ id: 3 },
{ id: 23 },
{ id: 16 }
];
let data = list.map((obj) => obj.id);
console.log(data);
In ES5:
var list = [
{ id: 1 },
{ id: 3 },
{ id: 23 },
{ id: 16 }
];
var data = list.map(function(obj) {
return obj.id;
});
console.log(data);

Categories