Push key value to the json array in Javascript - javascript

I have the json response as follows
{
"ProductDetails": [
{
"id": "1234",
"description": "Testing Product1",
"name": "Product1",
"displayName": "Product1",
"favourite": true,
"iconURL": "testNadIconURL",
"productType": "Application"
},
{
"id": "8754",
"name": "ProductFroGroup",
"displayName": "ProductFroGroup",
"favourite": false,
"productType": "Application"
},
{
"id": "8546",
"applicationURL": "http://example.com",
"description": "Test description",
"name": "ASO",
"displayName": "Product3",
"favourite": false,
"iconURL": "http://example/ux/images/phone-icon.png",
"productType": "Application"
}
]
}
JS
$ctrl.appList = response.data.ProductDetails;
for (var i = 0; i <= $ctrl.appList.length; i++) {
if ($ctrl.appList[i].iconURL != undefined) {
var valid = /^(ftp|http|https):\/\/[^ "]+$/.test($ctrl.appList[i].iconURL);
if (valid) {
console.log("URL avaibale");
} else {
$ctrl.appList[i].iconURL.push("http://example/ux/images/phone-icon.png");
}
} else {
$ctrl.appList[i].iconURL.push("http://example/ux/images/phone-icon.png");
}
}
I am trying to
To set the iconURL to a default url value if the iconURL is null.
Set the iconURL to the same default url if the iconURL is not available in the response.
I want to push both the key and value pair to each object of the array.

You can solve it in this way:
var regExp = /^(ftp|http|https):\/\/[^ "]+$/;
var appList = response.data.ProductDetails;
appList.forEach(function(app) {
var iconURL = app.iconURL || "";
if (!iconURL || !regExp.test(iconURL)) {
app.iconURL = "http://example/ux/images/phone-icon.png";
}
});
$ctrl.appList = appList;

Related

Fetch only specific objects from JSON via javascript or jQuery

I would like to fetch only specific objects from the below JSON such as only those JSON objects which have a classDefinition = "com.sap.bpm.wfs.UserTask". Please suggest on how to do this:
var metadata = {
"contents": {
"83eaead8-cfae-459b-9bdd-8b12e32d6715": {
"classDefinition": "com.sap.bpm.wfs.StartEvent",
"id": "startevent1",
"name": "StartEvent1"
},
"13583ac9-596d-4375-b9e1-e5f6f21e829f": {
"classDefinition": "com.sap.bpm.wfs.EndEvent",
"id": "endevent1",
"name": "EndEvent1"
},
"6c2b0935-444b-4299-ac8e-92973ce93558": {
"classDefinition": "com.sap.bpm.wfs.UserTask",
"subject": "Upload document",
"description": "{context.description}",
"priority": "MEDIUM",
"isHiddenInLogForParticipant": false,
"userInterface": "sapui5://html5apps/saptest/com.sap.test",
"recipientUsers": "I311520, I310811",
"id": "usertask1",
"name": "UserTask1"
},
"6728bf81-3d4e-4ae3-a428-1700a2096d34": {
"classDefinition": "com.sap.bpm.wfs.SequenceFlow",
"id": "sequenceflow1",
"name": "SequenceFlow1",
"sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
"targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
},
"aa99931e-2523-44c3-86b3-d522acdbde10": {
"classDefinition": "com.sap.bpm.wfs.ui.Diagram",
"symbols": {
"760f0725-3400-4d48-b082-5c69ad79d697": {},
"aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
"7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
"20c66c48-6058-465e-b500-d69d6e54c028": {},
"2e8f324c-5361-4512-a09a-fc7693f206ba": {}
}
}
}
};
First, metadata.contents property should rather be an array.
If you really cannot change it to an array, then use Object.keys(metadata.contents)
For example:
Object.keys(metadata.contents)
.map(x => metadata.contents[x])
.filter(x => x.classDefinition == 'com.sap.bpm.wfs.UserTask')
var metadata = {
"contents": {
"83eaead8-cfae-459b-9bdd-8b12e32d6715": {
"classDefinition": "com.sap.bpm.wfs.StartEvent",
},
"13583ac9-596d-4375-b9e1-e5f6f21e829f": {
"classDefinition": "com.sap.bpm.wfs.EndEvent",
},
"6c2b0935-444b-4299-ac8e-92973ce93558": {
"classDefinition": "com.sap.bpm.wfs.UserTask",
"subject": "Upload document",
"description": "{context.description}",
"priority": "MEDIUM",
"isHiddenInLogForParticipant": false,
"userInterface": "sapui5://html5apps/saptest/com.sap.test",
"recipientUsers": "I311520, I310811",
"id": "usertask1",
"name": "UserTask1"
},
"6728bf81-3d4e-4ae3-a428-1700a2096d34": {
"classDefinition": "com.sap.bpm.wfs.SequenceFlow",
},
"aa99931e-2523-44c3-86b3-d522acdbde10": {
"classDefinition": "com.sap.bpm.wfs.ui.Diagram",
}
}
}
var filtered = Object.keys(metadata.contents)
.map(x => metadata.contents[x])
.filter(x => x.classDefinition == 'com.sap.bpm.wfs.UserTask')
console.log(filtered)
A simple for loop can be used to get the desired fields:
var temp = [];
for (var index in metadata.contents) {
if (metadata.contents[index].classDefinition == "com.sap.bpm.wfs.UserTask") {
temp.push(metadata.contents[index]);
}
}
Or you can do one by one
var metadata = {
"contents": {
"83eaead8-cfae-459b-9bdd-8b12e32d6715": {
"classDefinition": "com.sap.bpm.wfs.StartEvent",
"id": "startevent1",
"name": "StartEvent1"
},
"13583ac9-596d-4375-b9e1-e5f6f21e829f": {
"classDefinition": "com.sap.bpm.wfs.EndEvent",
"id": "endevent1",
"name": "EndEvent1"
},
"6c2b0935-444b-4299-ac8e-92973ce93558": {
"classDefinition": "com.sap.bpm.wfs.UserTask",
"subject": "Upload document",
"description": "{context.description}",
"priority": "MEDIUM",
"isHiddenInLogForParticipant": false,
"userInterface": "sapui5://html5apps/saptest/com.sap.test",
"recipientUsers": "I311520, I310811",
"id": "usertask1",
"name": "UserTask1"
},
"6728bf81-3d4e-4ae3-a428-1700a2096d34": {
"classDefinition": "com.sap.bpm.wfs.SequenceFlow",
"id": "sequenceflow1",
"name": "SequenceFlow1",
"sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
"targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
},
"aa99931e-2523-44c3-86b3-d522acdbde10": {
"classDefinition": "com.sap.bpm.wfs.ui.Diagram",
"symbols": {
"760f0725-3400-4d48-b082-5c69ad79d697": {},
"aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
"7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
"20c66c48-6058-465e-b500-d69d6e54c028": {},
"2e8f324c-5361-4512-a09a-fc7693f206ba": {}
}
}
}
}
var content = metadata["contents"];
var subContent = content["6c2b0935-444b-4299-ac8e-92973ce93558"];
var classDef = subContent["classDefinition"];
alert(classDef);

Trying to pick data from a JSON response text

I'm trying to pick some data from my JSON response text which looks like this:
{
"status": "success",
"reservations": [
{
"id": "22959",
"subject": "SubjectName",
"modifiedDate": "2017-04-03T06:04:24",
"startDate": "2017-04-03T12:15:00",
"endDate": "2017-04-03T17:00:00",
"resources": [
{
"id": "17",
"type": "room",
"code": "codeName",
"parent": {
"id": "2",
"type": "building",
"code": "buildingName",
"name": ""
},
"name": ""
},
{
"id": "2658",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "2446",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3137",
"type": "realization",
"code": "codeName",
"name": ""
},
{
"id": "3211",
"type": "realization",
"code": "codeName",
"name": "name"
}
],
"description": ""
},
{
"id": "22960",
"subject": "subjectName",
"modifiedDate": "2017-04-04T06:04:33",
"startDate": "2017-04-04T10:00:00",
"endDate": "2017-04-04T16:00:00",
"resources": [
{
"id": "17",
"type": "room",
"code": "codeName",
"parent": {
"id": "2",
"type": "building",
"code": "codeName",
"name": ""
},
"name": ""
},
{
"id": "2658",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "2446",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
}
],
"description": ""
}
]
}
I've been trying to use JSON.parse() and go through the response text with a for-loop with no success. I need to pick the subject names, room names, building names and both student_group names.
This is what my code currently looks like:
var getData = {
"startDate":,
"endDate":,
"studentGroup": [
""]
};
var data = new XMLHttpRequest();
data.onreadystatechange = function () {
if (data.readyState == 4 && data.status == 200) {
try {
// Parse JSON
var json = JSON.parse(data.responseText);
// for-loops
for (var i = 0; i < json.reservations.length; i++) {
for (var x = 0; x < json.reservations[i].length;
x++) {
document.getElementById("test").innerHTML =
json.reservations[i].subject;
}
}
} catch (err) {
console.log(err.message);
return;
}
}
};
// JSON query
data.open("POST", "URL", true, "APIKEY", "PASS");
data.setRequestHeader('Content-Type', 'application/json');
data.send(JSON.stringify(getData));
This only prints the last subject name if I have more than 1 of them.
How should I do this?
Once you have your data parsed, forget it once was JSON. Now you have a JavaScript object.
Check data.status to make sure everything went well.
Loop over data.reservations and, inside that, over data.reservations[i].resources.
You should treat your parsed data as an object, so to get you going, this will get all unique student group names from all returned resources:
var studentGroups = [];
for (var i = 0; i < json.reservations.length; i++) {
if(json.reservations[i].resources != null){
for(var j = 0; j < json.reservations[i].resources.length; j++){
var resource = json.reservations[i].resources[j];
if(resource.type === "student_group"){
if(studentGroups.indexOf("groupName"))
studentGroups.push(resource.name);
}
}
}
}
}
Of course I'm not sure in what format you want to get your result (should this be a flat array or maybe another JSON, maybe only first value is important for you?), but I think you should already have an idea how to handle the topic.

How to check if both the value exists or only one value exists in JavaScript object

I have an Object as below :
{"user": {
"name": "Harry Peter",
"phoneNumber": "12345",
"products": [
{
"type": "card",
"accountId": "5299367",
},
{
"type": "Loan",
"accountId": "5299365",
},
{
"type": "card",
"accountId": "8299388",
},
]}
}
What I need to find out if the user has both loan and card or just loan as user product.
Is there any built in function in javascript or angular to find it.
is someone has any suggestion how to do it. Please help.
You could use the filter array method.
var obj = {
"user": {
"name": "Harry Peter",
"phoneNumber": "12345",
"products": [
{
"type": "card",
"accountId": "5299367",
},
{
"type": "Loan",
"accountId": "5299365",
},
{
"type": "card",
"accountId": "8299388",
},
]
}
};
var loans = obj.user.products.filter(function(product){
return product.type === "Loan";
});
console.log("Loans: " + loans.length);
// supposing that the user has either a Loan or a card. You could
// easily now find out if the user has only loans as below:
if(loans.length === obj.user.products.length){
console.log("The user has only loans");
}else{
var cards = obj.user.products.length - loans.length;
console.log("The user has "+loans.length+" Loan(s) and "+ cards+ " Card(s).");
}
For further info about this method, please have a look here.
What I need to find out if the user has both loan and card or just
loan as user product.
Based on the above snippet, by using the filter method and comparing the length of the loans with the length of the products, you can answer you question.
You can loop over products and get unique types
var data = {
"user": {
"name": "Harry Peter",
"phoneNumber": "12345",
"products": [{
"type": "card",
"accountId": "5299367",
}, {
"type": "Loan",
"accountId": "5299365",
}, {
"type": "card",
"accountId": "8299388",
}, ]
}
}
var result= data.user.products.reduce(function(p,c){
if(p.indexOf(c.type)<0) p.push(c.type)
return p;
}, [])
console.log(result)
You can try following
var obj = {
"user": {
"name": "Harry Peter",
"phoneNumber": "12345",
"products": [{
"type": "card",
"accountId": "5299367",
}, {
"type": "Loan",
"accountId": "5299365",
}, {
"type": "card",
"accountId": "8299388",
}, ]
}
};
var results = {};
obj.user.products.reduce(function(oldval, item) {
oldval[item.type] = true;
return oldval;
}, results);
console.log(results.card && results.Loan); // paints true
// Additionally, results have all the information about the unique value for type, hence, can be used as per the need
Same Iteration solution, but immediately gives you if type is different from Loan.
var obj = {"user": {
"name": "Harry Peter",
"phoneNumber": "12345",
"products": [
{
"type": "card",
"accountId": "5299367",
},
{
"type": "Loan",
"accountId": "5299365",
},
{
"type": "card",
"accountId": "8299388",
},
]}
};
function haveDifferentProducts(products){
var isDiff = false;
products.forEach(function(product){
isDiff = product.type != "Loan"; //checks if type not loan
});
return isDiff;
}
console.log(haveDifferentProducts(obj.user.products))
Use Array filter() method.
Working demo :
var jsonObj = {
"user": {
"name": "Harry Peter",
"phoneNumber": "12345",
"products": [
{
"type": "card",
"accountId": "5299367",
},
{
"type": "Loan",
"accountId": "5299365",
},
{
"type": "card",
"accountId": "8299388",
},
]
}
};
var totalLoan = jsonObj.user.products.filter(function(item){
return item.type == "Loan";
});
var totalCards = jsonObj.user.products.filter(function(item){
return item.type == "card";
});
if(totalCards.length < 1 && totalLoan.length < 0) {
console.log("Only loan");
} else if (totalCards.length > 0 && totalLoan.length < 1) {
console.log("Only card");
} else {
console.log("Both card as well as loan");
}

JSON array length

Here is my JSON array code
var App = [
{
"id": "123",
"caption": "Test",
"description": "Test Desc"
},
{
"id": "345",
"caption": "adsasdasd",
"description": ""
},
{
"id": "456",
"caption": "adsasdasd",
"description": ""
},
{
"id": "578",
"caption": "adsasdasd",
"description": ""
}
]
i tried with the following code
var obj = $.parseJSON(App);
alert(JSON.stringify(obj,4,null));
var AppLen = obj[i].length;
alert(AppLen);
but i didn't get any solution. Let me know if i missed any thing to get the JSON object array length.
your data is already json format:do like this
var App = [
{
"id": "123",
"caption": "Test",
"description": "Test Desc"
},
{
"id": "345",
"caption": "adsasdasd",
"description": ""
},
{
"id": "456",
"caption": "adsasdasd",
"description": ""
},
{
"id": "578",
"caption": "adsasdasd",
"description": ""
}
];
console.log(App);
console.log(App[0].length);// you can not get length from this because it is not array it's an object now.
var AppLen = App.length;
alert(AppLen);
obj.size() or obj.length
If that dont run try this: Length of a JavaScript object
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
var size = Object.size(myArray);

How to select json item from the array

From the below JSON, how can I retrieve title from the note and notes using a for loop and ajax to retrieve?
{
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{ "id": "1", "title": "Red House", "url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html" },
{ "id": "2", "title": "Joo Chiat", "url": "http://www.the-inncrowd.com/joochiat.htm" },
{ "id": "3", "title": "Bake", "url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery" }
]
}
I tried out the code below but it doesn't work - it either says:
is null
not an object
length is null
r not an object
var detail = eval(xmlhttprequest.responseText)
var rss = detail.infos.info
for(var i = 0; i<rss.length; i++)
startyear += rss[i].startyear
Use
for (i = 0; i < 3; i++) {
alert(JSON.infos.info[0].note.notes[i].title);
}
TRY IT HERE: JSFIDDLE WORKING EXAMPLE
BTW your JSON is not valid. Use this JSON:
var JSON = {
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{
"id": "1",
"title": "Red House",
"url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html"
},
{
"id": "2",
"title": "Joo Chiat",
"url": "http://www.the-inncrowd.com/joochiat.htm"
},
{
"id": "3",
"title": "Bake",
"url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery"
}
]
}
]
}
}
EDIT:
Here is what you want:
var infoLength= JSON.infos.info.length;
for (infoIndex = 0; infoIndex < infoLength; infoIndex++) {
var notesLength= JSON.infos.info[infoIndex].note.notes.length;
for (noteIndex = 0; noteIndex < notesLength; noteIndex++) {
alert(JSON.infos.info[infoIndex].note.notes[noteIndex].title);
}
}
Putting your json into an var called obj, use the following:
obj.infos.info[0].note.notes[0].title
http://jsfiddle.net/Znq34/
Well the "path" to the JSON notes array-like object is:
json.infos.info[0].note.notes;
So you could do something like:
var notes = json.infos.info[0].note.notes;
var titles = [];
for (var i = 0, len = notes.length; i < len; i++)
{
titles.push(notes[i].title);
}
alert('titles is: ' + titles.join(', '));
Fiddle: http://jsfiddle.net/garreh/uDxqD/
Are you using jQuery? ;-)
// Assuming your using "success" in ajax response
success: function(json)
{
var titles = $(json.infos.info[0].note.notes).map(function() {
return this.title;
}).get();
alert(titles.join(', '));
}
First count the length of notes
var len = jsonobject.infos.info.note.notes.length;
Then loops through and get
var title = jsonobject.infos.info.note.notes[i].title;

Categories