Skip to content

Commit 2158586

Browse files
authored
Adding array to array pluck operation. (#3868)
1 parent 99ffbc8 commit 2158586

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

integration/test_var_operations.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ def VarOperations():
2020
from reflex.ivars.base import LiteralVar
2121
from reflex.ivars.sequence import ArrayVar
2222

23+
class Object(rx.Base):
24+
str: str = "hello"
25+
2326
class VarOperationState(rx.State):
2427
int_var1: int = 10
2528
int_var2: int = 5
@@ -29,6 +32,7 @@ class VarOperationState(rx.State):
2932
list1: List = [1, 2]
3033
list2: List = [3, 4]
3134
list3: List = ["first", "second", "third"]
35+
list4: List = [Object(name="obj_1"), Object(name="obj_2")]
3236
str_var1: str = "first"
3337
str_var2: str = "second"
3438
str_var3: str = "ThIrD"
@@ -474,6 +478,7 @@ def index():
474478
rx.text(
475479
VarOperationState.list1.contains(1).to_string(), id="list_contains"
476480
),
481+
rx.text(VarOperationState.list4.pluck("name").to_string(), id="list_pluck"),
477482
rx.text(VarOperationState.list1.reverse().to_string(), id="list_reverse"),
478483
# LIST, INT
479484
rx.text(
@@ -749,6 +754,7 @@ def test_var_operations(driver, var_operations: AppHarness):
749754
("list_and_list", "[3,4]"),
750755
("list_or_list", "[1,2]"),
751756
("list_contains", "true"),
757+
("list_pluck", '["obj_1","obj_2"]'),
752758
("list_reverse", "[2,1]"),
753759
("list_join", "firstsecondthird"),
754760
("list_join_comma", "first,second,third"),

reflex/ivars/sequence.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,17 @@ def contains(self, other: Any) -> BooleanVar:
707707
"""
708708
return array_contains_operation(self, other)
709709

710+
def pluck(self, field: StringVar | str) -> ArrayVar:
711+
"""Pluck a field from the array.
712+
713+
Args:
714+
field: The field to pluck from the array.
715+
716+
Returns:
717+
The array pluck operation.
718+
"""
719+
return array_pluck_operation(self, field)
720+
710721
def __mul__(self, other: NumberVar | int) -> ArrayVar[ARRAY_VAR_TYPE]:
711722
"""Multiply the sequence by a number or integer.
712723
@@ -915,6 +926,26 @@ def create(
915926
)
916927

917928

929+
@var_operation
930+
def array_pluck_operation(
931+
array: ArrayVar[ARRAY_VAR_TYPE],
932+
field: StringVar | str,
933+
) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
934+
"""Pluck a field from an array of objects.
935+
936+
Args:
937+
array: The array to pluck from.
938+
field: The field to pluck from the objects in the array.
939+
940+
Returns:
941+
The reversed array.
942+
"""
943+
return var_operation_return(
944+
js_expression=f"{array}.map(e=>e?.[{field}])",
945+
var_type=array._var_type,
946+
)
947+
948+
918949
@var_operation
919950
def array_reverse_operation(
920951
array: ArrayVar[ARRAY_VAR_TYPE],

0 commit comments

Comments
 (0)