0

I want to display all values from array categories, but I always got [object object] or undefined. Here is code in last lines if statement, there is that problem in part between bracket [] when I want to call categories and type of categories is Object:

  const urlKeys = [...new URL(window.location.href).searchParams.keys()];

  let categories = [];

  let count = urlKeys.length;

  for (let i = 0; i < count - 1; i++) {
    categories.push({ type: paramsFromUrl.get('category' + i) })
  }  //Here I push elements in categories

  if (urlKeys[0] === 'allCategories') {
    document.getElementById('notice').innerText = "All categories included: [" + categories + "]";
    return viewsjs.createRestaurantCards(filterjs.findRestaurantsByCategory(await restaurantsjs.loadRestaurantsJSON(), categories));
  } //Here is problem

2 Answers 2

1

categories is an array of objects. If you want to convert that to a string, you need to do JSON.stringify

"All categories included: " + JSON.stringify(categories);

If you only want to display the type and not the whole object, then:

"All categories included: [" + categories.map(obj => obj.type) + "]";
Sign up to request clarification or add additional context in comments.

1 Comment

Thank u. This works!
1

You can’t concatenate an Array directly into a String; it’s simply not the way it works. Seems like you need join(), which would return another String that you can successfully concatenate into your broader string to write into the DOM:

document.getElementById('notice').innerText = "All categories included: [" + categories.join(", ") + "]";

4 Comments

Thank u, but this does not help, I still get result [object Object], [object Object],...[object Object]
JS has type coersion, so it'll join automatically. It is better to explicitly declare it, but it isn't causing the problem here.
@StephenK Then you’ve left some critical information out of your post; what type of data is contained in categories…?
@esqew console.log(typeof (categories)) when I type this I get Object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.