loop through array of objects and concatenate object property in spacce separated string in python

To loop through an array of objects and concatenate a specific property in a space separated string using Python, you can use a for loop and string concatenation. Here's an example:

main.py
my_array = [{ 'name': 'John', 'age': 28 }, { 'name': 'Jane', 'age': 24 }, { 'name': 'Bob', 'age': 31 }]
result = ''

for item in my_array:
    result += item['name'] + ' '

print(result) # Output: "John Jane Bob"
213 chars
8 lines

In this example, we first define an array of objects called my_array. We then create an empty string called result that we will use to store the concatenated values. We then loop through each item in the array, and for each item, we concatenate the value of the 'name' property with a space using the + operator. We then assign the resulting string to the result variable. Finally, we print the value of result which will be a space separated string of all 'name' properties in the array.

gistlibby LogSnag