arraysloopsobject

How can I loop over object keys in Xel scripts?


I'm making a project with Xel, but I am stuck on a problem.

I want to loop through the keys of an object, and here's a minimal example of what I'm trying to get:

const strings = import("xel:strings")

let obj = {
    key1: "value",
    key2: "value2,"
    key3: "value3"
}

let i = 0
// This "keys" function is hypothetical. I'm not sure what I should do here.
// "keys" might return an array
const allKeys = keys(obj)
while ( len(allKeys) > i ) {
    const key = allKeys[i]
    const value = obj[key]
    print(strings.format("%v: %v", key, value))
    i = i + 1
}

But this doesn’t seem to work... How can I achieve this?


Solution

  • In Xel, iterating over the keys of an object is a common requirement, especially when working with dynamic data structures. While earlier versions lacked native support for this functionality, recent updates have addressed the gap.

    Before Xel v0.13.0, looping over object keys in Xel was unfortunately not directly possible due to the lack of built-in object manipulation functions. However, I'm happy to announce that Xel v0.13.0 (released in 9th June 2025) introduces the xel:object module, which makes this task straightforward!

    Here's how you can achieve your goal using the new features:

    Solution

    
    const object = import("xel:object")
    const strings = import("xel:strings")
    
    let obj = {
        key1: "value",
        key2: "value2",
        key3: "value3"
    }
    
    const allKeys = object.keys(obj) // returns an array of keys
    
    let i = 0
    
    while (len(allKeys) > i) {
        const key = allKeys[i]
        const value = object.get(obj, key) // or obj[key]
    
        print(strings.format("%v: %v", key, value))
        i = i + 1
    }
    
    

    Explanatuon:

    1. object.keys(obj): This function from the xel:object module takes your object obj and returns an array containing all of its keys (property names).

    2. object.get(obj, key): We now use object.get(obj, key) to retrieve the value associated with a given key.

    Alternative Method:

    You can also use the object.entries() function and a forEach loop for a more concise solution:

    
    const object = import("xel:object")
    const strings = import("xel:strings")
    const array = import("xel:array")
    
    let obj = {
        key1: "value",
        key2: "value2",
        key3: "value3"
    }
    
    const entries = object.entries(obj) // returns an array of [key, value] pair
    
    array.forEach(entries, (entry) {
        const key = entry[0]
        const value = entry[1]
    
        print(strings.format("%v: %v", key, value))
    })
    
    

    This method uses object.entries() to get an array where each element is an array containing the key and value, then iterates over the entries using array.forEach() (introduced in earlier Xel releases).