The potential and options of functions organized and defined within an Array

I'm currently facing difficulties in organizing my code efficiently.

Let me illustrate the structure I have in mind:

var Test = {
  old: [
    get: function(who, when){
       returrn({ subject: "Old test 001", text: "The test 001 was perform by "+who });
    },
    get: function(who, when){
      returrn({ subject: "Old test 002", text: "The "+when+" the test 002 was performed"});
    }
  ],
  new: [
     //Same thing
  ]
};

The issue arises when trying to implement this structure as it seems not feasible. I am seeking advice on how to declare functions within an array. This is necessary because each method 'get()' of the array should return a different message and may include variables passed in parameters positioned differently within the text, thus requiring explicit declaration.

I've considered the following alternative approach:

var Test = {
  old: [
    one: {
      get: function(who, when){
        returrn({ subject: "Old test 001", text: "The test 001 was perform by "+who });
      },
    },
    two: {
      get: function(who, when){
        returrn({ subject: "Old test 002", text: "The "+when+" the test 002 was performed"});
      }
    }
  ],
  new: [
     //Same thing
  ]
};

This option does not meet my requirements as I need to access the content dynamically, like

Test.old[test_id].get("toto", "02/04/2013")
. Unfortunately, indexing items by numerical values in JSON is not allowed.

If there's no better solution, I will proceed with this setup.

In this context, what would be the most suitable approach?

Thank you!

Answer №1

Although the question is a bit unclear, it's evident why your code isn't functioning properly. The issue lies in mixing up arrays and objects. Here's how array literals are structured:

var myArray = [
  "first item",
  "second item",
  {value: "third item"},
  ["first/only item in fourth item"],
  1,
  2,
  3.14159,
  function(a,b) { return a + b; },
  "etc."
];

You interact with array items using push, pop, shift, unshift, and numerical indexes.

On the other hand, object literals appear like this:

var myObject = {
  one: "some value",
  two: {
    value: "object values can be anything"
  },
  123: 456,
  "a million": function (a, b) { return a - b; }
};

Access to object items requires string indexes.

Lastly, make sure you have a returrn() function defined somewhere. Otherwise, why not just return your return values directly?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing continual issues with login authentication on node.js and Express.js due to invalid credentials

I am still new to node.js and encountering an issue with fetching my login credentials from the database. Although I can retrieve the login credentials successfully, when I try to access them from my server.js file, I consistently receive an error statin ...

Is it possible to modify the stroke color of the progress circle in ng-zorro?

I am working on an Angular project where I aim to create a dashboard displaying various progress circles. Depending on the progress, I need to change the color of the line. Current appearance: https://i.sstatic.net/hR2zZ.png Desired appearance: https://i. ...

I encountered login issues when trying to access dist/index.html in my Angular 8 application, but I found a workaround by utilizing the proxy.conf.json file, which

I have been trying to login through the index.html page in the angular 8 dist folder, but I keep encountering an error with the login API URL. Despite spending two days on this issue, I have not been able to find a solution. If anyone has any suggestions o ...

Tips for referencing a string in JavaScript

I am trying to use the showmodal method, but I keep getting an error when passing a string. It works fine with integers, but how can I pass a string in JavaScript? <script> var table = ' <table id="example" class="table table-striped " w ...

Prevent the click event on an Angular component

I am currently utilizing the component found on this link: I have not been able to locate a function or property that disables the component state, making it impossible to select dates on the calendar. Due to this limitation, I am interested in learning ...

Managing loading and changing events using Angular, jQuery, and Web API

I am populating a dropdown select using ng-repeat. <select onchange="ChangeMonth()" id="month"> <option ng-repeat="(key,val) in Months" ng-selected="val==ActiveMonth" value="{{key}}"> {{val}} ...

"Is there an objective array that results in an undefined property of stdClass

When working with a JSON array that has been converted to an object array, I encountered an issue where trying to echo any property from the array resulted in an error. Undefined property: stdClass::$title Here is a representation of the array: stdClass ...

What is the most efficient way to generate multiple JSON payloads in Python by utilizing the input from sys.argv?

Challenge description: This is my approach to invoking prepare_payload.py : python3 prepare_payload.py ['Example1','Example2','Example3'] [https://10.5.5.1,https://10.5.5.2,https://10.5.5.3] ['xyz','abc',& ...

Performing the addition operation on two floating point numbers in JavaScript

The JavaScript code goes as follows: var receivedamt = parseFloat($('#cashRecText').val()).toFixed(2); console.log(receivedamt); var addon = parseFloat('5.00').toFixed(2); console.log(addon); addon = parseFloat(receivedamt).toFixed(2 ...

Error message: npm command not recognized while running commands within an Electron application

While developing an electron app, I utilize shell commands with child_process.exec. One of the commands I use is npm run start, which functions perfectly in a development environment. However, upon building the application for production, all npm commands ...

Is it possible to have the background scroll downward while keeping some content centered in place at all times?

Attempting to achieve the following effect in JavaScript, HTML, and Sass: When scrolling down the page, the layers (ground, sky, space, etc.) move downward The content (a rocket flying in the sky) stays centered on the screen and will move horizontally l ...

Node.JS comes with the ability to write text to a file, making

Just starting out with Node.js and have a JSON object that looks like this: var results = [ { key: 'Name 1', value: '1' }, { key: 'Name 2', value: '25%' }, { key: 'Name 3', value: 'some string&a ...

How can you access the URL of an ajax request in JavaScript/jQuery once the request has been completed?

I am currently working on a web program using JavaScript that involves making multiple ajax calls. I am faced with the challenge of figuring out how to retrieve the URL after making an ajax call to the specified URL. These ajax calls are made within a for ...

Guide to dynamically assigning v-on with v-for

I'm working on a Vue code that dynamically creates a menu using v-for, with each element requiring a different method when clicked. Here's what I have so far: <span v-for="(menuItem, index) in menuItems" :key="index"> ...

What is the best way to modify the values in an initialized array once the fetchData method has been executed?

As a beginner in Vue.js, I am currently working on a project that involves updating initialized arrays in the data() section of my component using the fetchData method. Below is a simplified version of the code: <script> import axios from 'axi ...

What is the best way to merge an array of objects into a single object?

Is there a way to dynamically convert object1 into object2, considering that the keys like 'apple' and 'water' inside the objects are not static? const object1 = { apple:[ {a:''}, {b:'&apos ...

Is it a common issue for JSON/JQuery requests with a setTimeout to consistently return a "null" result when using the Twitter Search API?

Upon making a call to the Twitter API, I retrieve 100 posts along with properties indicating the next page to be called. However, when I wait 5 seconds and make that subsequent call, the JSON results in the callback function always return null the second t ...

Uncover and control nested objects in JSON data

Having a dynamic foo object with the possibility of nested parent objects raises the question of how to effectively: 1) Determine the last object that has a parent? 2) Create an array containing all nested parent objects along with the initial obj (foo.o ...

JQuery Ajax call fails to retrieve any information

I have been experimenting with JQuery Ajax methods. I created a basic Ajax request to retrieve specific 'tagged' photos from Flickr. Here is the code snippet I am using: function initiateSearch() { $(function() { var tagValue ...

URL for requesting JSON data using Zend Framework

Just getting started with ZF1 and I'm tackling the task of obtaining a JSON response for a specific id. I have successfully retrieved all values from a table using the code below. The question now is, how can I pass a parameter from the URL? public ...