In this guide, we'll walk through how to automatically increment IDs when adding new objects to an existing array of objects using Xano's no-code platform. This can be useful when you need to maintain unique identifiers for elements within a collection, such as product attributes or order items.
Before we begin, make sure you have the following:
id propertyFor this example, we'll use a products table with a column called attributes that stores an array of objects with id, color, and size properties.
First, let's create a new API endpoint in Xano:
product: The name of the product you want to updatecolor: The color of the new attributesize: The size of the new attributeNext, we'll fetch the existing product record from the database:
field name to the column you're searching by (e.g., name).field value to the product input.This will retrieve the record containing the array of objects we want to modify.
To increment the ID, we'll need to:
id valueid by 1id and the provided color and sizeHere's how to do it in a single step:
field name to the column containing the array of objects (e.g., attributes).value to the following expression:push(
{{products1.attributes}},
set(
set(
{},
"id",
get(pop({{products1.attributes}}), "id") + 1
),
"color",
{{inputs.color}}
),
"size",
{{inputs.size}}
)
This expression does the following:
pop({{products1.attributes}}) gets the last object in the attributes arrayget(..., "id") retrieves the id value from that object... + 1 increments the id by 1set({}, "id", ...) creates a new object with the incremented idset(..., "color", {{inputs.color}}) adds the color property from the inputset(..., "size", {{inputs.size}}) adds the size property from the inputpush({{products1.attributes}}, ...) appends the new object to the existing attributes arrayYou can now test your API endpoint by providing a product name, color, and size. The new attribute should be added to the attributes array with an incremented id.
Once you're satisfied with the results, you can deploy your API and start using it in your applications.
Xano's no-code platform makes it easy to perform complex operations like incrementing IDs in an array of objects without writing any code. By following this guide, you should now be able to automatically generate unique identifiers when adding new elements to existing collections in your data models.
Join 100,000+ people already building with Xano.
Start today and scale to millions.
Start building for free