Adding array to array pluck operation. (#3868)
This commit is contained in:
parent
99ffbc8c39
commit
21585867b9
@ -20,6 +20,9 @@ def VarOperations():
|
||||
from reflex.ivars.base import LiteralVar
|
||||
from reflex.ivars.sequence import ArrayVar
|
||||
|
||||
class Object(rx.Base):
|
||||
str: str = "hello"
|
||||
|
||||
class VarOperationState(rx.State):
|
||||
int_var1: int = 10
|
||||
int_var2: int = 5
|
||||
@ -29,6 +32,7 @@ def VarOperations():
|
||||
list1: List = [1, 2]
|
||||
list2: List = [3, 4]
|
||||
list3: List = ["first", "second", "third"]
|
||||
list4: List = [Object(name="obj_1"), Object(name="obj_2")]
|
||||
str_var1: str = "first"
|
||||
str_var2: str = "second"
|
||||
str_var3: str = "ThIrD"
|
||||
@ -474,6 +478,7 @@ def VarOperations():
|
||||
rx.text(
|
||||
VarOperationState.list1.contains(1).to_string(), id="list_contains"
|
||||
),
|
||||
rx.text(VarOperationState.list4.pluck("name").to_string(), id="list_pluck"),
|
||||
rx.text(VarOperationState.list1.reverse().to_string(), id="list_reverse"),
|
||||
# LIST, INT
|
||||
rx.text(
|
||||
@ -749,6 +754,7 @@ def test_var_operations(driver, var_operations: AppHarness):
|
||||
("list_and_list", "[3,4]"),
|
||||
("list_or_list", "[1,2]"),
|
||||
("list_contains", "true"),
|
||||
("list_pluck", '["obj_1","obj_2"]'),
|
||||
("list_reverse", "[2,1]"),
|
||||
("list_join", "firstsecondthird"),
|
||||
("list_join_comma", "first,second,third"),
|
||||
|
@ -707,6 +707,17 @@ class ArrayVar(ImmutableVar[ARRAY_VAR_TYPE]):
|
||||
"""
|
||||
return array_contains_operation(self, other)
|
||||
|
||||
def pluck(self, field: StringVar | str) -> ArrayVar:
|
||||
"""Pluck a field from the array.
|
||||
|
||||
Args:
|
||||
field: The field to pluck from the array.
|
||||
|
||||
Returns:
|
||||
The array pluck operation.
|
||||
"""
|
||||
return array_pluck_operation(self, field)
|
||||
|
||||
def __mul__(self, other: NumberVar | int) -> ArrayVar[ARRAY_VAR_TYPE]:
|
||||
"""Multiply the sequence by a number or integer.
|
||||
|
||||
@ -915,6 +926,26 @@ class ArraySliceOperation(CachedVarOperation, ArrayVar):
|
||||
)
|
||||
|
||||
|
||||
@var_operation
|
||||
def array_pluck_operation(
|
||||
array: ArrayVar[ARRAY_VAR_TYPE],
|
||||
field: StringVar | str,
|
||||
) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
|
||||
"""Pluck a field from an array of objects.
|
||||
|
||||
Args:
|
||||
array: The array to pluck from.
|
||||
field: The field to pluck from the objects in the array.
|
||||
|
||||
Returns:
|
||||
The reversed array.
|
||||
"""
|
||||
return var_operation_return(
|
||||
js_expression=f"{array}.map(e=>e?.[{field}])",
|
||||
var_type=array._var_type,
|
||||
)
|
||||
|
||||
|
||||
@var_operation
|
||||
def array_reverse_operation(
|
||||
array: ArrayVar[ARRAY_VAR_TYPE],
|
||||
|
Loading…
Reference in New Issue
Block a user