0

I have this code that formats an array of objects, which is set out how I want it. However, when I go to return the output something strange happens. If I were to just return alert_cache, it returns null. But If I were return it like alert_cache.workflow_steps it returns the data needed.

Does anyone have any idea how to get around this?

if (alert_cache.length == 0) {
      alert_cache.workflow_steps = {}
      alert_cache.workflow_steps[keys.workflow_step] = { "errors": [], "last_error": {}};
      let alr = alert_cache.workflow_steps[keys.workflow_step];
      alr.errors.push(now)
      alr.last_error = {message: keys.message, url:alert.step_log_url}
}

return alert_cache;
2
  • 1
    How do you create alert_cache to start with? Commented Nov 26, 2019 at 16:05
  • 1
    "However, when I go to return the output something strange happens. If I were to just return alert_cache, it returns null. " The code above definitely doesn't return null if you do return alert_cache. It would fail (because alert_cache.length would throw a TypeError) or return non-null. Please update your question with a minimal reproducible example demonstrating the problem, ideally a runnable one using Stack Snippets (the [<>] toolbar button; here's how to do one). Commented Nov 26, 2019 at 16:06

1 Answer 1

2

You're using alert_cache like an array and like an object. You're checking length (as if it were an array):

if (alert_cache.length == 0) {

but you're also assigning to a non-element property:

alert_cache.workflow_steps = {}

Note that doing that will not change length.

You haven't shown how you create alert_cache to start with, but if it's an array, and if you're then using it with something that only looks at its array entries and not at its other properties (for instance, JSON.stringify), it will be empty (not null).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks man: alert_cache is initially set as an empty array. Once I get this working correctly, there will be a following else statement to append to the array of objects. I'm appending non-elemental values to it, correct. Is there a better solution to what I'm trying to do so that when I return alert_cache it returns what I need?
@fellinlovewithaman - Returning alert_cache isn't the problem, that'll work fine -- unless whatever's using it expects it to just be an array and doesn't use its non-element properties. What you're doing is fine in JavaScript, but not fine in most other environments, and won't survive conversion to/from JSON (for example). If you'd put an MRE in the question, we'd be able to help you better.

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.