0

How do I use a variable to make the following code reusable? Can I embed a variable in a template literal variable?

I am getting an object from the endpoint and I want to access object.CategoryName

here is my current code

export default function getCategoryAll(url, appendId, dataTitle, dataBody) {
    return $.ajax({
        url: url,
        type: 'GET',
        data: {

        },
        success: function (data) {
            console.log(data);
            // work here
            data.map((data) => {
                $(`#${appendId}`).append(`
                <div class="items-list-container">
                    <div class="items-list-content">
                    <div class="h5 items-list-content-title">${data + "." + dataTitle}}</div>
                    <div class="items-list-content-body d-flex"></div>
                    <button class="items-list-update-button badge btn btn-outline-success">Update</button></div>
                </div>`)
                return data
            })
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // Empty most of the time...
            $('#setting-category-list').append("<h4>Error!</h4>")
        }
    });
}

getCategoryAll("/getCategoryAll", "setting-category-list", "CategoryName")
  • 3
    What variable? And what's the problem in the first place? You already have two template literals with variables in them o.O – Andreas Feb 17 '22 at 08:08
  • @andreas The problem is that I want to access `data.CategoyName` but I am getting `[object Object].CategoryName` instead. Please help – ZemichaelMD Feb 17 '22 at 08:13
  • 2
    See [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable). Use `${data[dataTitle]}`. – Ivar Feb 17 '22 at 08:15
  • 2
    Why do people use `.map()` when you don't plan on using the array that it creates. Wasteful and wrong coding. Use `.forEach()` or, even better, just a plain `for` loop if you aren't trying to create a new result array. Ivar has the right answer for how to do `${data[dataTitle]}`. – jfriend00 Feb 17 '22 at 08:16

0 Answers0