Generate new variables by utilizing an array

Here is my array along with a loop that retrieves the keys (https://jsfiddle.net/ytm04L53/)

var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];

for (i = 0; i < feeds.length; i++) {
    var feed = feeds[i];
    alert(feed.match(/\d+$/));
}

https://i.sstatic.net/F4kB9.jpg

The length of the array may vary, and I want to either use these keys as variables and assign their corresponding values after the : colon, or create new variables and assign the values from these keys to them.

How can I accomplish this in order to perform comparisons such as:

if (test_user > 5000) {dosomething}

update Thank you for the responses. How can I also create a set of variables and assign the array values to them? For example, like the following:

valCount(feeds.split(","));

function valCount(t) {
 if(t[0].match(/test_user_.*/))
  var testUser = t[0].match(/\d+$/);
 }

Sometimes there may be only one key in the array, other times two or three, so t[0] will not always be test_user_

I need to pass the array to a function and check for matches. If a key starts with test_user_, then retrieve the value and assign it to a specific variable.

Thanks everyone for your assistance!

Answer №1

It is not feasible to generate dynamic variable names at runtime, although it is technically achievable.

Instead, you can opt for creating object properties:

var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];

var obj = {};
feeds.forEach(function(entry) {
    var parts = entry.split(":"); // Splits the string on the :
    obj[parts[0]] = parts[1];     // Establishes the property
});

Through this approach,

obj["test_user_201508_20150826080829.txt"]
now holds the value "12345".

Interactive Example:

var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];

var obj = {};
feeds.forEach(function(entry) {
    var parts = entry.split(":");
    obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- This script introduces the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Answer №2

Follow this example to achieve the desired result by utilizing the split method:

let index;
let items = ["example_item_20201012:54321", "sample_item_list20201012:987", "list_summary20201012.txt:654"];

for (index = 0; index < items.length; index++) {
    let item = items[index];
    console.log(item.split(/[:]/));
}

The above code will produce the following output:

["example_item_20201012", "54321"]
["sample_item_list20201012", "987"]
["list_summary20201012.txt", "654"]

Answer №3

To extract relevant information, utilize the split method

var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];

feedMap = {}
for (i = 0; i < feeds.length; i++) {
    var temp = feeds[i].split(':');
    feedMap[temp[0]] = temp[1];
}

The result will be:

{
    "test_user_201508_20150826080829.txt":"12345",
    "test_user_list20150826":"666",
    "test_list_Summary20150826.txt":"321"
}

You can access the data using the following structure:

feedMap["test_user_201508_20150826080829.txt"]

For further reference, check out this codepen link

Answer №4

If you're in a pinch and absolutely must generate variables dynamically, here's a workaround code snippet:

for (i = 0; i < feeds.length; i++) 
{
    var feed = feeds[i];
    window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}

alert(test_user_201508_20150826080829)

Do keep in mind that variable names cannot contain certain special characters such as '.'

Best, Michał

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

Using MongoDB's Aggregate function to retrieve multiple matching objects from an array

My goal is to achieve the same outcome as the user mentioned in this link. I have documents with a similar structure, containing an array of objects with multiple keys. What I aim to do is retrieve all objects within that array where a specific key's ...

What is the process for incorporating TypeScript typings into a snippet of jQuery code designed for a Bootstrap multilevel dropdown menu?

I'm exploring Angular for the first time and trying to create a multi-level dropdown using Bootstrap. I came across this article which contains some JavaScript code snippets that I am struggling with. I need help converting this code into TypeScript, ...

The default selection for React Material Multiselect items is not being chosen

Currently, I am working on implementing the React Material autocomplete component that includes a multiple-values checkbox. However, it seems like there is an issue with the defaultValue prop and the checkboxes example. Even though I set defaultValue to a ...

Attempting to transfer information between components via a shared service

Currently, I am utilizing a service to transfer data between components. The code snippet for my component is as follows: constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) { } ngOnInit() { this.psSe ...

Steps for incorporating Short Polling technique into Next 13 Server Component

I am currently facing an issue with my API fetch that runs every 3000ms using the setInterval method. The problem is that the component is not re-rendering with the latest data. Here is the code snippet: const Home = async () => { let customers = await ...

I am facing constant connection resets while attempting to upload a file to the Tomcat server

Exploring the creation of a website where users can freely post content has been an interesting journey. One challenge I'm currently facing is enabling users to upload files sequentially and send them as a multi-part request in ajax. Unfortunately, I ...

Retrieve data from a JavaScript generator-stream by applying a filter to the values

After watching a thought-provoking video on computerphile, I was inspired to try my hand at implementing the sieve algorithm using JavaScript generators. While I have experience with JavaScript, working directly with generators is a new challenge for me. ...

The V-model fails to reflect changes when the checkbox list is updated

I am facing an issue with my checkboxes that are generated dynamically in a component using a v-for loop. Once a checkbox is checked, it is added to an array of selected checkboxes. The problem arises when a checked checkbox is removed - the v-model still ...

Mastering JSON looping for each distinct group

I'm new to JavaScript and recently encountered an issue with JSON. Here is the object I am working with: var users = [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName": ...

Exploring the concept of finding the maximum value in an array using recursion in JavaScript

After some experimentation, I managed to create a function that uses recursion to find the maximum value in an array. const max = ([a,...rest]) => !rest.length || a > max(rest) ? a : max(rest); console.log(max([-3,3,19,61,99,22,55])); // 99 console ...

Is there a way to determine if an npm package is compatible with ES6 import syntax for importing?

Aside from reviewing the documentation of the package and trying different methods through trial and error, how can one be certain if an npm package can be imported using the ES6 import syntax? Is there a specific file within the package folder that can b ...

How can one retrieve an HTTP response by utilizing jQuery or JavaScript?

Having recently transitioned to web programming from a background in Java, I am now facing challenges in retrieving an HTTP response by accessing a specific URL. Despite referring to resources like the W3C schools, I have yet to achieve the desired result. ...

Looking for assistance with customizing my jQuery input styling

Check out this simplified version of the code: $(document).ready(function() { var $checkbox = $('input[type="checkbox"]'); $checkbox.wrap('<div class="stylecheck-container" style="display: inline" />').addClass('style ...

VM encounters unexpected issues when using 'require' function

Utilizing the native vm library, the following code enables javascript strings to be evaluated in various contexts. Within the code snippet found in example.js, there is a javascript string that adds a property .marker with the value true to the global var ...

Retrieving specific elements from an array and transferring them to a new array

As a beginner in the world of programming, I hope you don't mind me asking what may seem like a "noobish" question. I have recently come across an array that contains various values representing frequencies of occurrences - for example: {4, 5, 2, 7, 8 ...

What is the proper procedure for configuring Babel and executing "npm run dev" in the terminal without encountering the "ERROR in ./src/js/index.js" message?

My goal is to include the babel/polyfill with the index.js files using webpack. After completing the setup, I tried running "npm run dev" in the command prompt but encountered an error. The initial line of the error message said "ERROR in ./src/js/index.js ...

Utilizing the indexOf method to filter an array in a Next.js application with TypeScript

I have two arrays in my Next.js app Array 1: [ { identifier: "60a17722225f2918c445fd19", name: "Ben Awad", _id: "60c94480b8d43c28d0a6eb73 }, { identifier: "60a455d11fa62a1510b408f8", name: ...

Encountering difficulties accessing Node.JS Sessions

Hey there, I am currently working on integrating an angular application with Node.js as the backend. I have set up sessions in Angular JS and created my own factory for managing this. Additionally, I am utilizing socket.io in my Node.js server and handling ...

What is the best way to incorporate JavaScript files into a Java application?

Java applications execute Javascript code. However, the Jquery library is too lengthy to be accommodated in a String variable. I am able to read jquery.js from a file but unsure of how to bundle it within a .jar file. ...

Attention: The PageContainer component requires React component classes to extend React.Component

I recently started using react-page-transitions in my project and encountered the following warning message: "PageContainer(...): React component classes must extend React.Component." Here is a snippet of my code: import React from 'react'; ...