Looping through array of objects in Python coming from Javascript - javascript

Coming from Javascript I am trying to learn Python(very slowly). I'm trying to work out how to do a loop in Python script over an array of objects.
For example say I have the following object:
contacts = [{name:"John",age:30},{name:"Peter",age:20},{name:"Sarah",age:33}]
In javascript if I wanted to loop through the array and print to console each name I would do the following.
for (let i = 0; i < contacts.length; ++i) {
console.log(contacts[i][name])
}
Which would print out:
John
Peter
Sarah
Furthermore if I wanted to print the last name in the the list ie Sarah I would do the following
console.log(contacts[contacts.length-1][name])
My question is how would I do this in Python?

contacts = [{"name":"John","age":30},{"name":"Peter","age":20},{"name":"Sarah","age":33}]
for i in range(len(contacts)):
print(contacts[i]["name"])
for person in contacts:
print(person["name"])
The second way would be considered more "Pythonic".
EDIT - added to answer question in comment
To access only the last record in the list, use a negative offset.
print(contacts[-1]["name"])

Try using a for each loop
contacts = [{"name":"John","age":30},{"name":"Peter","age":20},{"name":"Sarah","age":33}]
for contact in contacts:
print(contact["name"])

Related

Understanding how to pull info from array

I have a previously created script that is doing API calls to get various info. Using json fetch. Its used to look up(GET) properties of users, groups, etc.
Here is how it prints. console.log(myArray):
[{user={conversion_id=smitht, ship_id=14.0, ship=Mountain , id=989, name=Smith, Todd, id=8745335.0, system_id=796663, login_id=todd.smith#domain.com,, created_at=3055-08-10, //keeps continuing for all users in this account
If I wanted to search the array and return only "name". Is there a better way to accomplish than this? This will print out just the names
for (let i = 0; i < myArray.length; i++){
console.log(myArray[i]['user']['name'])
I'm trying to learn what's possible and how to interact. Any other options to search through array? Most examples have sample arrays written out since mine comes from a response its been difficult to follow those examples.
use find https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
function findByLoginId(loginId) {
const result = myArray.find(user => user.login_id === loginId);
return result?.name;
}
Check to make sure that the fetched data is valid JSON. You should be able to use JSON.parse on the returned data.

Array from GroupsApp and then indexOf fails [duplicate]

This question already has answers here:
indexOf method in an object array?
(29 answers)
Why doesn't indexOf find an array within the searched array? (Need explanation not solution) [duplicate]
(3 answers)
Closed 1 year ago.
I am trying to get a list of people in a Google Group with Google Apps Script. I made a code (below) but the result is unexpected. I think is realted with the format of the item but not sure. In my code i tested many logs to check that.
Why "indexOf" can not detect properly the email? Becuase -1.00 as answer is wrong.
Info:
getUsers() User[] Retrieves the direct members of the group that have a known corresponding Google account.
I think is weird indexOf answering -1.00 when i ask with "" and when i ask with the position of array answer properly.
I need to check in an script if someone is inside of this groups (inside loop for).
function CheckingSomeFromGroup() {
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
Logger.log(members); //it shows an array in the log
Logger.log(members[0]); //it shows the first element form that array which is "Jorge#company.com"
Logger.log(members.indexOf("Jorge#company.com") //i was expecting a number different than -1.00 because jorge exists but in the log appear -1.00 which is wrong
Logger.log(members.indexOf(members[0]); //it shows 0 correctly becuase Jorge is in the first place of the array
Logger.log(members.length);//it shows number 3 which is ok since i have 3 people in the group
}
members is an array of User object, not string. So you cannot just find it by email/string. You see email in the logger because it might have a toString method to output that.
You can loop on members and call User.getEmail() to get the email and work accordingly.
function CheckingSomeFromGroup() {
var emails = ['abc#example.com'];//get 1-D array of string emails from your column accordingly
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
for (var i = 0; i < members.length; i++) {
var memberEmail = members[i].getEmail();
if (emails.indexOf(memberEmail) !== -1) {
//exists
}
}
}

Writing a function in two different ways: one way results in a TypeError and the other does not. Why?

I've come across an issue I don't understand what's going on. Here's the setup: the user enters the screen and inputs a last name. I take the last name and search a phone book (the entire phone book has been retrieved when the user enters the screen so it's just sitting there as a big, fat JavaScript array).
Let's assume each element of the phone book object consists of: a last name, first name and phone number. Now, I'll take the last name inputted by the user and loop across the phone book looking for the last names that match. I'll then push each matching element into an array and display that array to the user.
I've written the method to do this in two different ways. In the first way it returns the list of objects. In the second way (my preference), a TypeError is thrown.
Here is the first approach
$scope.getMatchingLastNames = function(){
for(i=0; i<$scope.phoneBook.length; i++){
if($scope.lastName==$scope.phoneBook[i].lastName){
$scope.filteredArray.push($scope.phoneBook[i]);
}
};
The second approach:
$scope.getList = function(){
$scope.filteredArray = getLastNames($scope.lastName,
$scope.phoneBook, $scope.phoneBook.length);
}
Which calls
function getLastNames(lastName, phoneBook, length)
{
var filteredArray = [];
for(var i=0; i<length; i++){
if(lastName==phoneBook[i].lastName){
filteredArray.push(phoneBook[i]);
}
}
return filteredArray;
}
When I run the second approach I'll get an error in Chrome console as follows:
TypeError: Cannot read property 'lastName' of undefined
And the error points to the if condition:
if(lastName==phoneBook[i].lastName)
Can someone explain to me why the second approach is resulting in an error?
Thanks.
Since what you are trying to achieve is to filter a list of results, I suggest you use angularJs filters
I prepared a jsfiddle for you with a simple example:
https://jsfiddle.net/fb0r7z0q/
This is the key line:
<li ng-repeat="entry in phonebook | filter:qname">
qname being your $scope.lastName

Iterating over Lua table in javascript with lua.vm.js

A while ago I posted a THIS question, regarding interaction between lua.vm.js and javascript.
Now I have a slightly different problem:
Lets assume that I have the following code in the REPL
model = {}
model['test1'] = 1
model['test3'] = 2
model['test4'] = 3
model['test5'] = 4
model['test6'] = 5
local window = js.global
window.model = model
Because I'm using lua.vm.js, I now that from javascript I can get all the values by doing
window.model.get('test1')
window.model.get('test2')
window.model.get('test3')
But the problem with that is that I have to know beforehand that the entries at the table are "test1", "test2", etc.
Is there a way in javascript(or maybe by adding some more Lua code) that I can iterate all over the table without knowing all the entries?
Thanks in advance!
I think the easiest way to get the list of keys in model would be to use Lua directly.
From what I can see the lua.vm.js table object does not support iteration, but you can do that from JavaScript:
my_keys = L.execute('local r = {}; for k in pairs(model) do r[#r+1] = k end; return unpack(r)')
Then you can loop like this:
for (var i in my_keys) {
console.log(my_keys[i], window.model.get(my_keys[i]));
}

Create an array of JavaScript objects from an existing array of objects

my first time posting a question here, so please let me know if I'm missing any information that is needed. Updated to include desired output.
I'm working on a google app script (basically javascript) and am trying to pull objects from an array of objects and create a new array of objects. I'm using the google base functions for getRowData (these can be found at : https://developers.google.com/apps-script/guides/sheets) to create my initial array of objects. This gives me a row of data similar (A JIRA export if anyone is wondering, with information cut):
{summary=Internal - Fix PuppetFile Jenkins Jobs, progress=1.0, issueType=Story, resolution=Done, timeSpent=3600.0, key=XXXXX-646, watchers=0.0, remainingEstimate=0.0, numberOfComments=1.0, status=Resolved, assignee=XXXXXXXX}
When I run my function:
for (var i = 0; i < issueList.length; i++){
rankList[i] = [issueList[i].summary,issueList[i].storyPoints,issueList[i].epicLink,issueList[i].fixVersions];
}
I get:
[Internal - Fix PuppetFile Jenkins Jobs, 3.0, null, null]
But what I want is:
{summary=Internal - Fix PuppetFile Jenkins Jobs, storyPoints=1.0, epicLink=StoryName, fixVersions=Done}
I'm not getting the key for the value, and I don't understand how the objects are constructed quite well enough to get it to transfer over. I looked at some examples of manipulating the key/value pairs but when I tried it on my own I just got a bunch of undefined. Thank you for any help you can provide.
What you want is probably something like this:
rankList = [];
for (var i = 0; i < issueList.length; i++) {
issue = issueList[i];
rankList.push({
summary: issue.summary,
storyPoints: issue.progress,
epicLink: issue.IDONTKNOW,
fixVersions: issue.resolution
});
}
I don't know what field goes in epicLink, since it wasn't obvious from your example. And I was just guessing about the other fields. But this is the general structure, you just need to make all the correct correspondences.
Use jquery each instead it's much easier to get the keys and value at the same time:
var myarray = [];
$.each(issueList,function(key,value){
console.log(key);
console.log(value);
value.key = key;
myarray.push(value);
});
console.log(myarray);

Categories

Resources