get element in array item ajax - javascript

I have a function writen in ajax that return a set of value:
$.each(data.dataa, function (i,item) {
$.each(item, function (index, dat) {
$str+=dat;
})
$ulSub.append( '<li id="'+item.id +'" class="ui-widget-content">' +$str+'</li>');
});
Each item has two attribute: the id and the lastname,
the value of each $str is a concatenation of the id and the lastname, but I want just the lastname not the id. I used the function item[2] but it's not working.
the result of my code is shwon as follow
What I want is just get the value of the lasname. I know that I should use item.lastname, but I want to ask if there are other methods to get the value of the lastname because the second attribute (lastname) is a variable.

Well, your case is quite simple, you always have an object with 2 properties: id and an unknown property. As objects do not have a defined order, you can´t assume that the field you want is always in second position
One way is to iterate the keys, and pick the one that is not equal to id:
for(var key in item){
if(key != 'id'){
$str+= item[key]
}
}
A similar way is to pick the object keys, and filter out the id one, then access the object with that key:
$str+= item[Object.keys(item).filter(function(k){return k != 'id'})[0]]
If you know the possible values of the key, another way would be:
var possibleKeys = ['lastname', 'name', 'adress', 'phonenumber']
for(var key in item){
if(possibleKeys.indexOf(key) != -1){ // if its a valid key, append the value
$str+= item[key]
}
}
In your case, the first option is probably the best, but there are mutiple ways to do it

Related

Remove element from named values in javascript

I have the following function, which is called when a google forms is submitted. I'm trying to concatenate all answers into a single array that's gonna be used latter:
function onFormSubmit(e) {
var respostas = e.namedValues;
for(item in respostas){
rp = rp.concat(respostas[item]);
}
}
But I would like to drop the timestamp that comes together with the answers. I can access it with respostas['Timestamp'], but I can't find a way to drop or ignore it. The documentation didn't help much.
var cp = [];
function onSubmitForm(e) {
var respostas = e.namedValues;
for (var name in respostas) {
if (respostas.hasOwnProperty(name) {
if (name !== 'Timestamp') {
cp.push(respostash[name]);
}
}
}
}
This is what I would suggest. Using concat to add an item is overkill, you can just push it. Also is a good practice when you are looping over object properties to make sure that they are its own properties of that object, not inherited from prototype. You can read more about it here
You can check the name of the property before concatenate it with the rest.
If the key item equals Timestamp (the undesired property) just skip the current loop.
for(item in respostas) {
if (item === 'Timestamp') {
continue;
}
rp = rp.concat(respostas[item]);
}
EDIT: Based on comments, OP attests that item in the for..in loop is a integer, but, unless his/her code differs radically from the docs, the variable should hold strings, not numbers.
var respostas = {
'First Name': ['Jane'],
'Timestamp': ['6/7/2015 20:54:13'],
'Last Name': ['Doe']
};
for(item in respostas) {
console.log(item);
}
e.namedValues returns a JSON Object with custom keys.
var jsonObj = e.namesValues;
/* e.namedValues returns data like this...
{
"test1": "testval1",
"test2": "testval2",
"test3": "testval3",
}
*/
for(item in respostas){
Logger.log(item); //Key
Logger.log(respostas[item]); //Value
}
This should let you access the key or value on the items in respostas.
The accepted answer is better as it does more to help the user to fix their exact problem, however, I will leave this here for future users in case they want to understand how to access the variables in the object that Google Apps Scripts returns.

Get value from javascript nested array

I am new in coding JavaScript. So far I know how to set and get values from a multi array, but with this one I cannot find the right way to do it.
I am trying to get the email value from this array:
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
I tried
JSON.parse(__ar.tag.email)
document.write(__ar[2][2])
Everything I tried so far I got either undefined or tag[object, object].
What's the easiest way to get it?
The email property is located on the second element of the array (that is index 1 of the zero based indexed array). So, to access it, you also need to access the second object of the element (again index 1) and then .email is at your hand:
document.write(__arr[1][1].email);
Assuming that you only push those two values, your array looks like the following:
[
['id' ,'12541'],
['tag', {"sub":false,"email":"email#email.com"}]
]
Means, that when you access it using __arr.tag.email will result in an undefined error, because it's an array not an object.
Therefore what you could do is, if you don't know exactly the index:
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
for (var i = 0; i < __arr.length; i++){
if(__arr[i][0] === 'tag'){
console.log(__arr[i][1].email);
break;
}
}
so you have an array as __arr, the first element you are pushing is id which is an array second array is having your email id.
so you can access as shown below.
I hope this will solve your issue
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
console.log("email id =>", __arr[1][1].email)
I hope you know array is starting from its index that's base value is 0. in your code there is no such element which is available in index 2.
document.write(__ar[2][2]) //
I know lots of answer is given here, but i just want to tell you even you are pushing value in "__arr" i.e an array of array. so every element is storing in its index value.
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
console.log(__arr[0]) //return you ["id", "12541"]
console.log(__arr[1]) //return you ["tag", {sub: false, email: "email#email.com"}]
again you can see inside of your "__arr" there is a an array element
console.log(__arr[0][0]) //return you "id"
console.log(__arr[0][1]) //return you "12541"
console.log(__arr[1][0]) //return you "tag"
console.log(__arr[1][1]) //return you {sub: false, email: "email#email.com"}
and here what you want i.e.
console.log(__arr[1][1].sub) //return you false
console.log(__arr[1][1].email) //return you "email#email.com"
A dynamic way to do it (with level of 2 nested levels).
Basically, I used two nested loops and aggregated the emails into a list.
let __arr = []
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
__arr.push(['tag2', {"sub":false,"email":"2222#email.com"}]);
const emails = __arr.reduce((res, items) => {
items.forEach(elem => {
if (elem.email) res.push(elem.email)
})
return res
},[])
console.log(emails)
// [ 'email#email.com', '2222#email.com' ]

JQuery array, accessed through a variable?

Im trying to populate a select (with the values from an array) depending on the option they select from the first dropdown
I have the arrays in my function, like so:
residential = ["R1_:_Single_Private_Dwelling","CH1_:_Self-Catering_Holiday_Unit","R2_:_Flats_or_Maisonettes_Up_to_3_floors_Purpose_Built","R3_:_Flats_or_Maisonettes_4_floors_and_over_Purpose_Built","CC7_:_Time_Share_Complex","R4_:_Houses_Converted_to_Flats_Up_to_2_Floors","R5_:_Houses_Converted_to_Flats_3_floors_and_over","MR_:_Hostel","R6_:_HMO","CC_:_Camping_Site","CC1_:_Caravan_Park","CC5_:_Chalet_Park","CC6_:_Caravan_And_Chalet_Park_","CC_:_Gypsy_Caravan_Site","XX1_:_Other"]; institutionalVal = ["MH2_:_Hospital","MH3_:_Hospital_(private)","MR1_:_(Care)_Home_for_older_people_(Over_65)","MR2_:_(Care)_home_for_adult_placements_"];
The user is selecting from a dropdown, with an ID of 'residential' for example and I want to populate a second select with the values from the array above.
So I'm grabbing the ID of the selected option, like so:
var org_cat = $(this).children(":selected").attr("id");
So, the value of org_cat for example would be 'residential', so I'm thinking i can just try and iterate through this as the array is called 'residential'
So I'm trying to loop through the array as below:
$.each(org_cat, function(value) {
$('#area_usage')
.append($("<option></option>")
.attr("value", value)
.text(value));
});
BUT, the variable 'org_cat' is not being seen as the array.
What am i doing wrong, do I have to tell JQuery that its an array somehow?
This is the error I'm getting.
TypeError: invalid 'in' operand a
What you are trying to do is referencing the variable "residential" (that is an array) by using a string. So for that you can have an object like:
var org_cat = $(this).children(":selected").attr("id"); // = "residential"
var obj =
{
"residential": ["R1_:_Single_Private_Dwelling","CH1_:_Self-Catering_Holiday_Unit","R2_:_Flats_or_Maisonettes_Up_to_3_floors_Purpose_Built","R3_:_Flats_or_Maisonettes_4_floors_and_over_Purpose_Built","CC7_:_Time_Share_Complex","R4_:_Houses_Converted_to_Flats_Up_to_2_Floors","R5_:_Houses_Converted_to_Flats_3_floors_and_over","MR_:_Hostel","R6_:_HMO","CC_:_Camping_Site","CC1_:_Caravan_Park","CC5_:_Chalet_Park","CC6_:_Caravan_And_Chalet_Park_","CC_:_Gypsy_Caravan_Site","XX1_:_Other"]; institutionalVal = ["MH2_:_Hospital","MH3_:_Hospital_(private)","MR1_:_(Care)_Home_for_older_people_(Over_65)","MR2_:_(Care)_home_for_adult_placements_"];
}
And get the array "residential" thought referencing the index in the object like:
obj[org_cat]
So on the jQuery each:
$.each(obj[org_cat], function(value) {
$('#area_usage')
.append($("<option></option>")
.attr("value", value)
.text(value));
});
Or if your variable "residential" is global, you can refer it through window object like window[org_cat] instead of obj[org_cat]

Find values in multidimensional array

Assume I have an array in my script and it's made up like this:
var detail= {};
detail['i100']=new Array()
detail['i100']['ID 4564']= 'John'
detail['i100']['ID 4899']= 'Paul'
detail['i100']['ID 9877']= 'Andy'
detail['i100']['ID 1233']= 'Evan'
detail['i25'] = new Array()
detail['i25']['ID 89866']= 'Paul s'
detail['i25']['ID 87866']= 'Paul'
I then use this script to get the values of the first part of the array:
$.each(detail, function(vehicle) {
console.log( vehicle )
});
This gives me two results as expected (i100 and i25), What I want to do however is, by using the reference vehicle, get all the names and values of the second dimension –
i.e. by using i25 I want to return ID 89866 and ID 87866. I have tried children(), but it is just not working. Does anyone have any advice, please ?
You need to run another each on the 2nd dimension.
$.each(detail, function(index,value){
$.each(value, function(i,v) {
console.log(v);
});
});
or if you want to specifically call one item, pass in the value name:
function getByName(name){
$.each(detail[name], function(i,v){
console.log(v);
});
}

Iteration Of JSON Array Of Objects Not Working

I have an array of objects that should be looking like this...
[{"Name":"blah","Description":"blah"},{"Name":"blah2","Description":"blah2"}]
Using Javascript/jQuery, how can I get the key/value pairs? I've tried many different ways but to no avail. When I try to get the length, it always returns the character count and iterates through each character and not the actual count of objects? When I run this, it returns an alert for [object Object], [object Object] spelled out by each character....
function DisplayItems(data) {
$.each(data, function () {
$.each(this, function (key, value) {
alert(value);
});
});
}
Now that I look at this, is it not the array of objects I'm expecting? How can I actually return the string so I can actually see what's really in it and maybe go from there?
**EDIT:
This is my function to get the orders (cut out the crap and showing you an alert)... I call jQuery.Ajax and pass the returned data to displayOrders(data). The orders have a composite property of Items containing a list of Item.
function displayOrders(data) {
$('#gdvOrders tbody').empty();
for (var key in data.d) {
alert(data.d[key].Items);
}
This is what I passed to displayItems, what you see in the alert function. I display the Orders in one table (hiding some columns including the Items), and want to display the Items for each order in another table when they select a row in the orders table. In the function shown above I can write...
data.d[key].OrderId
and it will display as normal. How do I display the properties for each item?
The jQuery.Ajax function is set to content-type: 'application/json; charset=utf-8' and this is where I get the orders from...
[WebMethod]
public static List<Order> GetOrdersByDept(Department department, Filter filter, DateTime? dateFrom = null, DateTime? dateTo = null)
{
return OrderLists.GetOrdersByDepartment((Department)department, (Filter)filter, dateFrom, dateTo);
}
See this is working:
data=[{"Name":"blah","Description":"blah"},{"Name":"blah2","Description":"blah2"}]
data.forEach(function(i,j){
console.log("Name :"+i.Name+" Description :"+i.Description);
})
Using JavaScript, simply use the for .. in loop
for(var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
alert(key + " = " + obj[key]);
}
}
}
Fiddle here - http://jsfiddle.net/XWsvz/
Now that I look at this, is it not the array of objects I'm expecting? How can I actually return the string so I can actually see what's really in it and maybe go from there?
If the object is being returned as a string, you can simply alert it. However, if your function is being passed an unknown object, you can always convert it back to a JSON string and alert it so that you can visualize the structure:
function displayItems(data) {
alert(JSON.stringify(data));
...
}
As a sidenote, I changed the first letter in your function to a lowercase letter to match naming conventions for functions in JavaScript.
Looks like you're close:
function DisplayItems(data) {
console.log('data is: ', JSON.stringify(data));
$.each(data, function (key, arrayElement, index) {
console.log('arrayElement ' + index + ' is: ', JSON.stringify(arrayElement));
$.each(arrayElement, function (key, value) {
console.log('key: ' + key + ' val: ' + value);
});
});
}
http://jsfiddle.net/ux9D8/
With your data this gives me the following output:
data is: [{"Name":"blah","Description":"blah"},{"Name":"blah2","Description":"blah2"}]
arrayElement undefined is: {"Name":"blah","Description":"blah"}
key: Name val: blah
key: Description val: blah
arrayElement undefined is: {"Name":"blah2","Description":"blah2"}
key: Name val: blah2
key: Description val: blah2

Categories