Get row number of json data - javascript

I have a ajax request which returns data in json format like
{
"response_code": 1,
"response_data": {
"ext": [
{
"client_id":"1003",
"company_name":"Reachmediagg"
},
{
"client_id":"1004",
"company_name":"RaSpecial"
}
],
"row_count":2
},
"response_error":""
}
As you can see the data is inside the ext array inside json object, now I have to get the row number of the data, so I want for example row number of client_id 1004, which is 2. How will I do that in javascript?

You have to loop through the ext array in your JSON and find the element that holds the correct client_id. The function described below does just that.
function get_row_number(data, client_id) {
var ext = data.ext;
// Loop through all the clients and try to find the one with the given client_id
for (var i = 0; i < ext.length; i++) {
if (ext[i].client_id == client_id)
return i;
}
// Return -1 if the client_id could not be found
return -1;
}

Technically the data doesn't have row numbers. Only in how you read the data can you infer/assign a row number.
Note that ext is an array. You can loop over that array until you find the record you want and keep a counter. For example:
var counter = 0;
for (;counter <= response_data.ext.length; counter++) {
if (response_data.ext[counter].client_id == 1004) {
break;
}
}
// here "counter" is the "row number" where client_id == 1004
You can also extract this into a function where the target client_id is a parameter (or the condition itself is a parameter, allowing you to look for more than just client_id).

Related

How to verify the length of attributes in an array and make sure no extra attributes are displayed?

I have verified the length of input as var resp =(body.input).length and make sure it is not 0. But I also want to verify only firstname,lastname and rollno is available in each set and the count will be always 3. How to I verify this is postman Test?
Response body:
{
"success": true,
"input":[
{
firstname:"Ram"
lastname:"Lakshmanan"
rollno: "11"
},
{
firstname:"Pravi"
lastname:"Reshma"
rollno: "12"
}
]
}
My Test looks like below:
var i;
for(i=0 ; i< resp ; i++){
var resp_firstname = body.input[i].firstname;
pm.test("Verify first name is available and not empty",function(){
pm.expect(resp_firstname).to.exist;
pm.expect(resp_firstname).to.not.eql();
}
First of all response body provided in the question is not the valid JSON.
Valid json data should look like this =
{
"success":true,
"input":[
{
"firstname":"Ram",
"lastname":"Lakshmanan",
"rollno":"11"
},
{
"firstname":"Pravi",
"lastname":"Reshma",
"rollno":"12"
}
]
}
you could do it like-
pm.test("Verify object has expected properties", function () {
// loop through input array
for (var i = 0; i < Object.keys(json.input).length; i++) {
console.log(i);
pm.expect(json.input[i]).to.have.property("firstname");
pm.expect(json.input[i]).to.have.property("lastname");
pm.expect(json.input[1]).to.have.property("rollno");
//assert length of properties
pm.expect(Object.keys(json.input[i]).length).to.eql(3);
}
});

Replicating MySQL array formatting in Javasript

I have 5 mysql tables that i need a variety of data from in several different scripts that all reference each other using an id's located in 1 or more column.
I need to create a master query that replicates the array structure exactly as it was imported from mysql AND ALSO needs error handling for each field before it writes to an array to determine if it needs to write the value to an array, or write it as null.
So far the script is looking like this:
const items = [];
// Items
for (let i = 0; i < gameItems.length; i++) {
if (gameItems[i].id) {
items.push({ id: gameItems[i].id });
} else {
items.push({ id: null });
}
if (gameItems[i].identifier) {
items.push({ identifier: if (gameItemParams[i].custom_name)
{
items.push({ custom_name: gameItemParams[i].custom_name });
}
else {
items.push({ custom_name: null }); }
}
}
The problem, or my lack of ability to figure out the logic on how to execute the code correctly, is that in order to attach multiple fields of data to the same row in an array the values must be comma separated.
Individual pushes like above add data to the next row instead of the same object which renders the array.length properly useless because there is a new row for every single field so instead of having 1 row with 10 pieces of data attached, i would have 10 rows each with 1 piece of data.
Is there a way to perform error handling for each field i need to call from the tables or is there another way to add data to the same object after a row has already been pushed.
This is how the newly created array must be structured:
https://puu.sh/E7ogn/61c3117d3b.png
This is how the array is currently being structured with individual pushes:
https://puu.sh/E7oh7/422541a70d.png
Maybe if it is possible to break in the middle of an array.push i can then add error handling in the push block but was unable to find if it can be done.
The problem is that you are pushing an object every time. Instead of that, you need to create an object with all of fields and then push it to the array.
Other problem of your code is that you can use an if statement into a assigment statement. You need to use a conditional operator to do that or extract this conditional from the assigment.
const items = [];
// Items
for (let i = 0; i < gameItems.length; i++) {
var object = {};
if (gameItems[i].id) {
object.id = gameItems[i].id;
}
else {
object.id = null;
}
if (gameItems[i].identifier) {
object.identifier = (gameItemParams[i].custom_name) ? items.push({ custom_name: gameItemParams[i].custom_name }); : items.push({ custom_name: null });
}
items.push(object);
}
As per the data mentioned in https://puu.sh/E7oh7/422541a70d.png.
You have data like
gameItems=[{id:0}, {identifier:"master-ball"}, {category_id:34}, {"custom_name":"Master Ball"}];
I suggest that instead of making items as an array, Please create temporary object item and then push it to items.
let items = [];
let item = {
id:null,
identifier: null,
custom_name: null
};
for (let i = 0; i < gameItems.length; i++) {
if (gameItems[i].id !== undefined) {
item.id = gameItems[i].id;
}
if (gameItems[i].identifier !== undefined) {
item.identifier = gameItems[i].identifier;
}
if (gameItems[i].custom_name !== undefined) {
item.custom_name = gameItems[i].custom_name;
}
}
items.push(item);

Change string into array

I am beginner in Angular and TS.
I want to get array of integer like [1,2,3,4] , but jasper server gives an output as string "[1,2,3,4]".
So how I change it using Type Script.
Data :
[
{
LABEL:'CR FAILURE MESSAGES',
DATASET:'[3,3,10,15,21,35,35,81]'
},
{
LABEL:'CR SUCCESS MESSAGES',
DATASET:'[1,4,31,34,63,78,219,312,1076]'
},
{
LABEL:'CR TOTAL MESSAGES',
DATASET:'[4,7,55,66,93,98,300,312,1086]'
},
{
LABEL:'PR FAILURE MESSAGES',
DATASET:'[2,5,6,12,18,19,23,48]'
},
{
LABEL:'PR SUCCESS MESSAGES',
DATASET:'[4,5,10,22,32,65,101,139]'
}
]
You can use JSON.parse to do this for you.
let obj = {
"LABEL":"CR FAILURE MESSAGES",
"DATASET":"[3,3,10,13,21,35,35,81]"
};
let datasetArray = JSON.parse(obj.DATASET); // Generates the array
console.log(datasetArray);
Is there a reason why you get an array wrapped in a string? If the server just returned a stringified JSON object, I would expect that calling JSON.parse on the whole thing would just build the array inline with the rest of the object.
Here's my solution
You can remove the first and the last characters to get "1,2,3,4" and then use split in order to turn it into array
The code is well commented take your time to understand it line by line;
var input = "[3,3,10,13,21,35,35,81]"
console.log(input)
//cleaning the input
var cinput = input.substr(1).slice(0, -1);
console.log(cinput)
//using split to turn it into an array by using the ',' as seperator
var output = cinput.split(',')
//the result
console.log(output)
var parsedarray = []
//to parse each array element to int
for (var i = 0, len = output.length; i < len; i++) {
parsedarray[i] = parseInt(output[i]);
}
//parsed numbers inside the array
console.log(parsedarray)

Look for item value in localstroge

I have a $localstroge with the below stored value:
{"EmployerDetails":{"Distance":30,"EmpLatitude":51.3353899,"EmpLongitude":-0.742856,"EmpNo":39424,"Insitution":null,"PlaceName":"Camberley","TalentPoolLicences":[{"Membership":[{"Identity":39424,"Name":"Weydon Secondary School"}],"TalentPoolType":1},{"Membership":[{"Identity":2,"Name":"North East Hampshire"},{"Identity":4,"Name":"Surrey"},{"Identity":8,"Name":"Surrey"}],"TalentPoolType":3}]},"FacetFilters":{"LastActivity":0,"LocationFilterType":1,"fullorparttime_pex":null,"religion":null,"soughtphase_swk":null,"soughtrole_swk":null,"soughtsubject_swk":null},"LookingFor":null,"OrderBy":null,"PageIndex":1,"PageSize":40}
How can I get the Identity value out from it that sits inside EmployerDetails. I have tried below but it never gets inside if condition:
for (var i = 0; i < localStorage.length; i++) {
if (localStorage.getItem(localStorage.key(i)) === 'EmployerDetails')
{ console.log('hello'); }
}
Any help on this please?
As you're searching for nested key first you need to grab the object and also need to parse it to JSON with JSON.parse then you can proceed as we do in case on normal javascript object
localStorage.getItem('signup-prefs')
This gives me a string containing my object
""name":"google","oauth_version":"2.0","oauth_server":"https://accounts.google.com/o/oauth2/auth","openid":"","username":""}"
After parsing it we can get the object and now we can find the desired property.
JSON.parse(localStorage.getItem('signup-prefs'))
Object {name: "google", oauth_version: "2.0", oauth_server: "https://accounts.google.com/o/oauth2/auth", openid: "", username: ""}
Coming to your problem
Let's say your employee information is like this i am not showing all the fields here.
var empData = {"EmployerDetails":Distance":30,"EmpLatitude":51.33538}}
Then you set the key like this
localstorage.setItem('empData', JSON.stringify(empData))
Now get the string object by key parse it to Json and find the desired key from the object loop over it to get the result.I haven't tested it but i am confident it will work. Let me know if not.
for (var i = 0; i < localStorage.length; i++) {
if (localStorage.key(i) === 'empData') {
// Parse the string to json
var empData = JSON.parse(localStorage.getItem('empData'));
// get all the keys
var keys = Object.keys(empData);
for (var idx = 0; idx < keys.length; idx++) {
// find the desired key here
if (keys[idx] == 'EmployeeDetails') {
var empDetails = empData[keys[idx]]
}
}
}
}
One important thing about your code is
this statement localStorage.key(i)) === 'EmployerDetails' returns either true or false and writing like this
if(localStorage.getItem(localStorage.key(i)) === 'EmployerDetails') will never was executed because you didn't have any key with that name(In practice we should never use keyword as key) .
Did you try to convert it to the json object and then gets the values out?

Unique names are not coming in jqgrid filter functionality

I have implemented the filter functionality in jqgrid. The logic is like to iterate on the data of the grid and then find the unique values for the filter. By selecting the values present in the filter we can apply the filter. But One of the strings that is present in the column is coming twice and they are exactly same. For e.g. row 1 : "ABC", row 2: "ABC",row 3: "DEF", row 4: "DEF", row 5 :"FEG" The values in the filter should be ALL,ABC,DEF,FEG but i am getting ALL,ABC,ABC,DEF,FEG. DEF is not repeating. So is it the problem with the string or something else. The code is
getUniqueNames = function(columnName) {
var data = $("#grid0").jqGrid('getGridParam', 'data');
var uniqueTexts = [], text, textsMap = {}, i;
for (i = 0; i < data.length; i++) {
text=data[i][columnName];
if (text !== undefined && textsMap[text] === undefined) {
// to test whether the texts is unique we place it in the map.
textsMap[text] = true;
if (typeof text =="string" && text.trim()!=''){
uniqueTexts.push(text);
}
}
}
// Object.keys(textsMap); Does not work with IE8:
return uniqueTexts;
}

Categories

Resources