Код: Выделить всё
#[wasm_bindgen]
pub fn sort_json_array(arr: JsValue, key: &str, ascending: bool) -> JsValue {
// Deserialize the JsValue into a Vec
let mut objects: Vec = from_value(arr).unwrap_or_default();
// Sort the objects by the specified key
objects.sort_by(|a, b| {
let a_val = a.get(key).unwrap_or(&Value::Null);
let b_val = b.get(key).unwrap_or(&Value::Null);
// Perform type-aware comparison
match (a_val, b_val) {
(Value::String(a_str), Value::String(b_str)) => {
if ascending {
a_str.cmp(b_str)
} else {
b_str.cmp(a_str)
}
}
(Value::Number(a_num), Value::Number(b_num)) => {
if ascending {
a_num.as_f64().partial_cmp(&b_num.as_f64()).unwrap_or(std::cmp::Ordering::Equal)
} else {
b_num.as_f64().partial_cmp(&a_num.as_f64()).unwrap_or(std::cmp::Ordering::Equal)
}
}
(Value::Bool(a_bool), Value::Bool(b_bool)) => {
if ascending {
a_bool.cmp(b_bool)
} else {
b_bool.cmp(a_bool)
}
}
_ => std::cmp::Ordering::Equal, // Default to equal for unsupported types
}
});
let json_object = Value::Object(&objects);
// Serialize the sorted objects back into JsValue
to_value(&json_object).unwrap() //[{}]
}
вместо объекта json {} его возврата, как карта , и я хотел бы передать дополнительный тип параметра , если тип является строкой , я заинтересован в вызове строки и аналогично для номера и подлим к усилению времени. alt = "this" src = "https://i.sstatic.net/hbl8puoy.png"/>
, как ожидается, как
Подробнее здесь: https://stackoverflow.com/questions/795 ... nside-rust
Мобильная версия