Looking for a method to select a random value from an array of objects without having to go through the entire parent array?

As a JavaScript newcomer, I am seeking assistance with a particular task.

The array of objects in question looks like this:

    const data =
{
    "Total_packages": {
        "package1": {
            "tags": [
                "kj21",
                "j1",
                "sj2",
                "z1"
            ],
            "expectedResponse": [
                {
                    "firstName": "Name",
                    "lastName": "lastName",
                    "purchase": [
                        {
                            "title": "title",
                            "category": [
                                "a",
                                "b",
                                "c"
                            ]
                        }
                    ]
                }
            ]
        },
        ...
    }
}

    var arrRand = genNum(data, 3);
    console.log(arrRand);

               function genNum(data, loop='') {
                    ...
               }

        }

To access the necessary values, I use expressions like arrRand[0].tag and arrRand[0].response.

However, duplicate responses are common in the output, which can be problematic.

[
  
]

My objective is to make API requests with a randomized "tags" value from the list above and then compare the response to the expected one.

Initially, I considered something like:

data.Total_packages.tags[Math.floor(Math.random() * data.Total_packages.tags.length)];

Yet, directly accessing "tags" without traversing through its parent, such as "package1" or "package2," makes it non-random.

I realize there must be a simpler solution that eludes me. Any guidance would be greatly appreciated.

Answer №1

One way to approach this is by creating an array with tags elements and using it for various random operations.

const data =
{
    "Total_packages": {
        "package1": {
            "tags": [
                "kj21",
                "j1",
                "sj2",
                "z1"
            ],
            "expectedResponse": [
                {
                    "firstName": "Name",
                    "lastName": "lastName",
                    "purchase": [
                        {
                            "title": "title",
                            "category": [
                                "a",
                                "b",
                                "c"
                            ]
                        }
                    ]
                }
            ]
        },
        "package2": {
            "tags": [
                "s2",
                "dsd3",
                "mhg",
                "sz7"
            ],
            "expectedResponse": [
                {
                    "firstName": "Name1",
                    "lastName": "lastName1",
                    "purchase": [
                        {
                            "title": "title1",
                            "category": [
                                "a1",
                                "b1",
                                "c1"
                            ]
                        }
                    ]
                }
            ]
        }
    }
}

const arrayOfTags = Object.entries(data.Total_packages).reduce((acc, [k, v]) => {
  if (v.tags) acc = acc.concat(v.tags.map(t => ({tag: t, response: v.expectedResponse})));
  return acc;
}, []);

const randomIndex = Math.floor(Math.random() * arrayOfTags.length);

const randomTag = arrayOfTags[randomIndex];

console.log(randomTag.tag, randomTag.response);

Answer №2

To extract and randomize tags before retrieving the value from them, you can follow these steps. Assuming that your tags are arrays nested within

data.Total_packages[whateverpackage]
:

const data =
{
    "Total_packages": {
        "package1": {
            "tags": [
                "kj21",
                "j1",
                "sj2",
                "z1"
            ],
            "expectedResponse": [
                {
                    "firstName": "Name",
                    "lastName": "lastName",
                    "purchase": [
                        {
                            "title": "title",
                            "category": [
                                "a",
                                "b",
                                "c"
                            ]
                        }
                    ]
                }
            ]
        },
        "package2": {
            "tags": [
                "s2",
                "dsd3",
                "mhg",
                "sz7"
            ],
            "expectedResponse": [
                {
                    "firstName": "Name1",
                    "lastName": "lastName1",
                    "purchase": [
                        {
                            "title": "title1",
                            "category": [
                                "a1",
                                "b1",
                                "c1"
                            ]
                        }
                    ]
                }
            ]
        }
    }
}

let tags = [];
for (let key in data.Total_packages) {
    if (data.Total_packages[key].tags) tags = tags.concat(data.Total_packages[key].tags);
}
console.log(tags[parseInt(tags.length * Math.random())]);

EDIT

You mentioned duplicates in the comments like:

[
  {
    "tag": "s22",
    "response": [
      {
        "firstName": "Name4",
        "lastName": "lastName4",
        "purchase": [
          {
            "title": "title4",
            "category": [
              "a4",
              "b4",
              "c4"
            ]
          }
        ]
      }
    ]
  },
  {
    "tag": "dsd31",
    "response": [
      {
        "firstName": "Name2",
        "lastName": "lastName2",
        "purchase": [
          {
            "title": "title2",
            "category": [
              "a2",
              "b2",
              "c2"
            ]
          }
        ]
      }
    ]
  },
  {
    "tag": "dsd31",
    "response": [
      {
        "firstName": "Name2",
        "lastName": "lastName2",
        "purchase": [
          {
            "title": "title2",
            "category": [
              "a2",
              "b2",
              "c2"
            ]
          }
        ]
      }
    ]
  }
]

To remove duplicates, use this approach:

let input = [
  {
    "tag": "s22",
    "response": [
      {
        "firstName": "Name4",
        "lastName": "lastName4",
        "purchase": [
          {
            "title": "title4",
            "category": [
              "a4",
              "b4",
              "c4"
            ]
          }
        ]
      }
    ]
  },
  {
    "tag": "dsd31",
    "response": [
      {
        "firstName": "Name2",
        "lastName": "lastName2",
        "purchase": [
          {
            "title": "title2",
            "category": [
              "a2",
              "b2",
              "c2"
            ]
          }
        ]
      }
    ]
  },
  {
    "tag": "dsd31",
    "response": [
      {
        "firstName": "Name2",
        "lastName": "lastName2",
        "purchase": [
          {
            "title": "title2",
            "category": [
              "a2",
              "b2",
              "c2"
            ]
          }
        ]
      }
    ]
  }
];

let output = input.filter((item, index) => {
    return input.filter((item2, index2) => {
        return ((item.tag === item2.tag) && (index2 < index));
    }).length === 0;
});

console.log(output);

We identify and eliminate items with earlier matches.

Answer №3

Storing all tags in a separate array, I retained the reference of expectedResponse within the block. The next step involved randomly selecting a tag index and matching it with the corresponding block's expectedResponse index. While there may be some tweaking needed for the random/length parameters, this code snippet should point you towards the right path.

let tagsArray = [];
let blockData = Object.values(data.Total_packages).flat();
blockData.forEach(item => tagsArray = [...tagsArray, ...item.tags]);

let randomIndex = tagsArray[parseInt(tagsArray.length * Math.random())];
console.log(blockData[Math.floor(tagsArray.indexOf(randomIndex) / 4)].expectedResponse);

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

What is the best way to compare two 2D arrays in JavaScript?

Having an issue comparing two 2D arrays in javascript, looking to output "true" if the arrays are the same. This is the code I experimented with: ` function check(){ if (data.every() === solution.every()){ alert("example"); } else { ...

jquery implementation of an interactive form with dynamic event triggers

I am completely new to jQuery and I know this might be a basic question, but I'm struggling to find a solution. Here's what I want to achieve: I need to create a form where if a user selects 'yes' from a dropdown menu, more fields will ...

Click the mouse to create a unique path from the list items within the <ul> <li> using jQuery

My current listing contains various files and folders: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fon ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

Strange behavior of a occluded object in three.js

After utilizing the three.js library, I successfully displayed occluded edges of a 3D object as dashed lines. Now, my goal is to make edges occluded by other objects behave in the same manner. Although the solution provided here is functioning well, ther ...

Guide to removing all elements belonging to a specific class on a webpage using Google Chrome

If I have elements on a website I am using with classes 'aaa', 'bbb', and 'ccc', and I want to delete or hide all elements with the class 'bbb', how can I accomplish this by changing attributes of elements directly o ...

How can I limit the input of string values from a Node Express request query?

export type TodoRequest = { order?: 'asc' | 'desc' | undefined; } export const parseTodoRequest = (requestData: ParsedQs): TodoRequest => { return { order: requestData.order as 'asc' | 'desc' | u ...

Clicking on the menu in mobile view will cause it to slide upward

I have implemented sticky.js on my website and it is working well. However, when I resize the browser to mobile view and click the main menu button, it goes up and I am unable to close it. I have to scroll up to see it again. How can I make it stick to the ...

Accessing a nested value in MongoDB: A step-by-step guide

I am working on a document where I have a category object containing fields for category name, cost, and date. My task is to retrieve categories specifically from the year "2022". The console is currently showing "[]" output, but I want it to display categ ...

JavaScript - Dynamically Disable Select Option Elements Depending on the Selected Option

I'm currently working on a form that includes two select elements. Each of these select elements contains multiple options with corresponding values. The first select element, identified by the id "average," has five options while the second one, iden ...

Combining an Image with a CanvasJS Graph and Generating a Downloadable Image of the Composite

I am attempting to combine an image (a background image for my graph) with my canvasJS chart. Once these elements have been merged on a canvas, I aim to obtain a DataURL of this canvas, enabling me to download an image of it (depicting the graph along wit ...

What is the advantage of parsing values in a switch statement compared to an if condition?

function checkInput() { let value = document.getElementById('test').value; if (value == 1) { console.log("It works with if statement"); } } function checkSwitch() { let value = document.getElementById('test').value; switc ...

jQuery-powered Ajax file upload progress bar

Although I don't rely on jQuery for everything, I do find it useful for tasks such as AJAX. But currently, I'm facing some challenges with it. Here is a piece of code that should update my upload progress bar while the upload process is ongoing. ...

Guidelines on Sharing Redux Store with Client during Routing in Redux

I'm currently learning Next.js and facing an issue with maintaining the dispatched state on a newly built page after routing. Can anyone provide guidance on how to retain the state? Specifically, I have a sidebar where I want to preserve the state of ...

An Array Selection That Fails to Display Results

I am currently working on a CRON job that needs to run daily. The job involves checking a MySql table for a specific date in the 'FAPforSale_repost35' field. If the date matches today's date, the job will proceed to delete photo images from ...

Is it feasible in AngularJS to compel a view to refresh without using the controller associated with it?

UPDATE: The title question has been correctly answered below. In order to provide a helpful example, I will keep the original question along with the answer below. My current framework does not completely abstract the Angular variable-to-camelcase conven ...

Troubleshooting JSON Array Index Problems

I'm having trouble reaching index 3 in the array using the javascript options on my webpage. The final question "are you satisfied with your choice?" is not showing up for me. I'm not sure what I might be missing or doing incorrectly in this sit ...

Sort an array in C++ using QuickSort algorithm without altering the original array (without the use of a temporary array)

Typically I wouldn't turn to Stack Overflow for help with my school assignments, but this task seems impossible without manipulating the array or using a temporary array. The requirements are: A recursive QuickSort Function It must sort the arr ...

Create a function within jQuery that triggers when an option in a select field is chosen

As I edit a podcast, I have encountered a situation where an option is being selected through PHP code. Now, I am looking to implement jQuery functionality for when the option is selected from the select field. I have searched through various questions an ...

Spring framework experiencing issues with loading CSS and JavaScript files

I'm facing an issue with my Spring-MVC application where the CSS and JS files are not loading even though they are correctly called. Can anyone help me figure out what I'm doing wrong? Resources folder: Project --> webapp --> resources - ...