Replace single value from text list field Using JS to Bubble

I am building a function to have a data structure that is a list of text. When attempting to make changes to the list of text, I ran into a poor UX, which is that it is not possible to change a particular text value in the list and keep the list in the same order.

I used the toolbox plugin and JS to Bubble element to make it possible using the code below

function replaceValueInList(originalList, targetValue, newValue) {
    // Ensure the input is an array or a string that can be converted to an array
    if (typeof originalList === "string") {
        // If the input is a comma-separated string, convert it into an array
        originalList = originalList.split(",").map(item => item.trim());
    }

    if (!Array.isArray(originalList)) {
        console.error("The provided list is not a valid array or a comma-separated string.");
        return;
    }

    // Replace the target value with the new value while keeping the order
    const updatedList = originalList.map(value => value === targetValue ? newValue : value);

    // Convert the updated array into a JSON string
    const updatedListJSON = JSON.stringify(updatedList);

    // Send the updated list as a JSON string back to Bubble
    if (typeof bubble_fn_updatedList === "function") {
        bubble_fn_updatedList(updatedListJSON);
    } else {
        console.error("JavaScript to Bubble function 'bubble_fn_updatedList' is not defined.");
    }
}

// Example usage (replace with dynamic data from Bubble):
const originalList = "123, 456, 789"; // Input list as a comma-separated string
const targetValue = "456";            // Value to replace
const newValue = "555";               // New value

// Call the function
replaceValueInList(originalList, targetValue, newValue);

Note, on the JS to Bubble I am using the value as a single value and not a list

The dynamic values in the javascript from above


Regex pattern: "([^"]+)"
find and replace is just finding the quotation mark and replace value is empty

need the join with operator as a comma and space to create the list of text to add into DB

examplechangetextlist-ezgif.com-video-to-gif-converter

2 Likes

Sweet solution! I’ve not messed with this exact problem but I’m curious if you do this if you can achieve it in pure bubble.

Below Parent group just refers to the host data type the list of text is in.

List = Set list = parent group list:converted to text:find and replace (old value you want to change with new value):join with (,)

Essentially taking the list from a list to a text string, replacing the values and keeping order, then reformatting it into a list again.

On the converted to text you may need to add :formatted as text
(this text),

I’m not at a computer this is just off top of my head so please excuse the rough concept :sweat_smile:

@boston85719

I tried this…basically if my list has values such as 123, 456, 123456, 789, 123456789 and I attempt to change the value of 123, then the values of 123456 and 123456789 also get changed because the :find and replace will take the original value of 123 and replace that with the replacement value in all values in the list of text that contain the original value, which means, changing 123 to 321 will also change 123456 to 321456 and 123456789 to 321456789

1 Like

Very could point, did not consider this scenario :raised_hands:

Try using a Regex expression in the find and replace.

I have something similar set up for my pseudo JS values. ChatGPT is great at generating regex expressions.

1 Like

It’s all set up and working. Do you have a regex expression that would do this?

@boston85719 the whole point of this exercise being to save a repeating list group items at the same time correct?

Couldn’t handle myself!
Did in just 3 steps with pure Bubble.
See if works for you.

Editor: Here

1 Like

is there a good reason why you’re using a single text and the split by operator instead of an actual list of text? why not set “value is a list” to true in the js to bubble plugin. then ask chatgpt to rewrite this same function, but to accept an array. just place 2 sqaure brackets, and between them, a dynamic expression (this assumes that the updated list’s value is also an array now): Js Edit Container ID Updated List's values each item: formatted as json safe. now, js to bubble spits out an array that you save to the database. i see that in your use case, you only accept numbers, but in general, it’s better to use formatted as json safe in the old and new value in the js too instead of writing the quotes yourself

1 Like

This is what I see on the link you provided…it seems to use 5 steps and the Ultimate Toolkit plugin…Do you have a version that uses pure Bubble and does it in 3 steps?

The example was just numbers, the setup works for any combination of letters, numbers and special characters

Couldn’t get chatgpt to do that successfully…if you can take the code and have chatgpt alter it to work with js to bubble as a list please share here the code. I tried myself for more time than I was willing to waste on it, while the setup I have works just fine, just requires me to remove the square brackets and the quotes.

No, it is to change a single value in a list of texts (ie: a data field that is of type text and is a list) and not have the list of texts order change.

Yeah…

Surely it’s easier, and more efficient, to use an array here…

Then just find the index of the item (using findIndex()) and reassign the value for that item.

Here’s a demo: Demo

Editor

Here’s the regex I got
(?<=^|\|\|)\s*(daynamic_value)\s*(?=\|\||$)

I use || as a delimiter in the demo as that’s my usual practice for this sort of things.

ChatGPT does have a little issue with Bubble regex but you can guide it with this Bubble regex Doc.

1 Like

There are 5 steps so you can see what I am caching. The toolbox is just for this purpose. You can simply save the variables in some custom state… no big deal. Nothing hard to do… as I said, pure Bubble.

Thanks for that…this works great. Now two approaches in the toolbelt

How is this done? Would be great to get another working example on this tip thread

Assuming you have a list of texts: (e.g.)

let myList = [
  'item 1',
  'item 2',
  'item 3',
  'item 4'
]

etc.

Then you can use the following:

function updateList(originalValue, newValue) {
  let index = myList.findIndex(item => item === originalValue);
  myList[index] = newValue;
}

And then invoke the function, with the intended parameters e.g.

updateList('item 2', 'item 406');

To change ‘item 2’ to ‘item 406’

you probably also want to include a check to make sure the item to change actually exists, to avoid any potential issues… such as:

function updateList(originalValue, newValue) {
  let index = myList.findIndex(item => item === originalValue);
  if (index >= 0) {
    myList[index] = newValue;
  } else {
    console.log(`Item ${originalValue} not found`);
  }
}
2 Likes

This kind of “programming” is really not the best way. If it works for your scenario that is great. But just for future travelers, findIndex will only return the first found item. If your list can contain duplicate values (e.g. 123, 234,345, 123,457), and the user tried to replace the second “123” in this scenario, the first 123 would actually be replaced and the second would be left as is.

Based on the fact that the OP has a list of ID’s I would assume these will all be unique, but what if the user accidentally types 123 twice not realizing it and then tries to correct it later? It could lead to a confusing experience.

If you use a field that is a list in bubble it is not possible to have duplicates

In my setup, the user is able to see all the IDs they have recently added and are already stored in the database, in the event an existing item in the list is the same as a newly added item (added not to db but in the RG) they see both and can alter it if they spot it, but since it saves to a field, the duplicate doesn’t actually create a duplicate.

BTW, @bubble.trouble do you have an alternative approach that also works, that doesn’t require ‘programming’…so far best solution in this thread is from @ihsanzainal84 with the use of the regex expression, and I personally plan to return to this thread to utilize that approach in the future if I need the functionality again. But at the end of the day, the more workable solutions there are, the better as some may be better suited for different use cases.

1 Like

I’m not sure what that’s supposed to mean,…

And you haven’t offered any ‘better’ solution here…

findIndex() returns the index of the first item matching the condition - which is EXACTLY what’s needed here.

why would there be more than one item in the list with the same ID (although, personally I always use object arrays for this, not strings) - and what would the intended behaviour be if there were duplicate IDs in the list?

In any case, that’s an entirely different question - but obviously if you need to change Multiple items then a different method needs to be used.

If you do this right, in my opinion/experience it really is the best way to do it (much simpler, cleaner, and more efficient than any alternatives I’ve seen or tried).

But I’d be interested to hear your ‘better’ way…