Obtain the value of a string using JavaScript

I need help passing a string value as a function parameter and using it inside the function.

Below is the code snippet:

UPDATE:


var array = [{someValue: 5}, {someOtherValue: 10}];
var newArray = [];
var obj = {value: "someValue"};
var setValue = function(choosenValue) {

for (let i = 0; i < array.length; i++) {
   newArray.push({
   choosenValue: array[i].choosenValue
  });
}

}

setValue(obj.value);

UPDATE: I am aiming to achieve newArray=[someValue : 5]; I want to generate a new array from an existing array with a key passed as a parameter. The chosenValue should represent the value inside the existing array, and I aim to access its value. The desired output should be an array of objects with identical keys but varying values.

The value from the object will vary based on the chosen key, so I need to iterate through the array. Since the chosenValue is in string format, I may encounter issues when looping through the array.

I have attempted using choosenValue.valueOf(), but it did not yield the expected result. Any alternative suggestions?

Currently, I am encountering an issue inside push() as choosenValue appears to be undefined.

Answer №1

It seems like you're unsure about the desired functionality of your code, so I'll make some assumptions based on what you've provided.

Let's analyze the code snippet from your question:

var array = [{someValue: 5}, {someOtherValue: 10}];
var newArray = [];
var obj = {value: "someValue"};
var setValue = function(choosenValue) {

    for (let i = 0; i < array.length; i++) {
        newArray.push({
            choosenValue: array[i].choosenValue
        });
    }

}

setValue(obj.value);

From this code, it appears that you want to populate the newArray with values based on the 'choosenValue' property in the objects stored in the 'array'. However, the logic you're trying to implement is more suited for a Map or Dictionary data structure rather than an Array.

Instead of using an array like

var array = [{someValue: 5}, {someOtherValue: 10}]

You could utilize a map like

var map = { someValue: 5, someOtherValue: 10 }

This way, you can directly access values by keys such as map.someValue or map[choosenValue].

The current loop in your code attempts to retrieve the 'choosenValue' property from each object in the array. However, since the objects in the array have different property names ('someValue', 'someOtherValue'), accessing 'choosenValue' will result in 'undefined' values.

If you intend to extract values based on specific properties, you should revise the loop to something like:

var array = [{ someValue: 5, someOtherValue: 10 }, 
             { someValue: 6, someOtherValue: 12 }];
var newArray = [];
var setValue = function(choosenValue) {

    for (let i = 0; i < array.length; i++) {
        newArray.push(array[i][choosenValue]);
    }
}

Now, each iteration retrieves the value specified by 'choosenValue' from the objects in the array.

If your goal is to create new objects containing the specified field name along with its value, you need to construct the object first and then set the field using bracket notation:

for (let i = 0; i < array.length; i++) {
    var temp = {};
    temp[choosenValue] = array[i][choosenValue];
    newArray.push(temp);
}

While not the most elegant solution, this approach achieves the desired outcome.

1 - In situations where an object only holds one field and you plan to access that field individually, it may be preferable to extract the field directly instead of retaining it within an enclosing object. Encapsulation is beneficial when passing the entire object or planning future expansions.

Answer №2

To utilize a dynamic key, you must declare it in an "array" format.

newArray[choosenValue] = array[i][choosenValue]

Your updated code should look like this:

for (let i = 0; i < array.length; i++) {
    newArray[choosenValue] = array[i][choosenValue]
}

It's important to note that although newArray is an array for you, you actually want to populate it with objects by keys. Therefore, the correct approach is to make newArray an object.

var result = {}

for (let i = 0; i < array.length; i++) {
   result[choosenValue] = array[i][choosenValue]
}

Complete Example

var result = [];
var array = [{hello:"hello"}, {world:"world"}, {hello:"hello2"}];
var setValue = function(value) {
    for (let i = 0; i < array.length; i++) {
       if (array[i][value]) 
          result.push(array[i][value]);
    }
}
setValue("hello");
console.log("Result", result);

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

Bidirectional data binding of textarea in AngularJS

To gather user responses to a list of questions, I created a form. Here is the HTML form: <div class="list" ng-repeat="question in questions.data.Question" > <div class="item item-divider"> {{question.text}} </div> ...

span tag used within a Twitter Bootstrap 2 modal

Using span structure in modal view is causing overflow issues when using .row, .row-fluid, or spans within the modal. <div id="login_register_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&g ...

Updating textures dynamically in Three.js

My current project involves creating a user interface where users can change the texture of a selected object by clicking on the desired texture image. However, I am facing a challenge where I can only access and use the last texture added in the array. ...

Separate by individual words or symbols using regex

Can someone assist me in precisely breaking down the expression -(ab | c) & d -> (d|c)&e <-> f into individual elements within an array? ['-', '(', 'ab', '|', 'c', ')', &apos ...

Automatically fill in a form according to the value chosen from a drop-down list using Jquery and Ajax

I'm diving into the world of AJAX and jQuery for the first time. I've managed to code a feature that auto-populates a combo box using an AJAX call in the form I'm working on. Now, I want to automate the rest of the fields in the same form ba ...

Using AngularJS to convert a JSON object into an array

Hey there, I've got a JSON return object that looks like this: color_selected = [ { id: 4}, { id: 3} ]; Any tips on how I can convert it to the following format? color_selected = [4,3] Appreciate any help or s ...

Error: Unable to access the 'login' property of an undefined object

An error occurred: Uncaught TypeError: Cannot read property 'login' of undefined........... import Login from '../components/Login.jsx'; import { useDeps, composeWithTracker, composeAll } from 'mantra-core'; export const com ...

Tips for accessing Java server side functions through HTML/JS and Android?

I am looking to embark on a personal project involving a Java-coded server, an HTML/JS client (with a framework yet to be determined), and an Android client. My goal is to have the ability to call a Java method from both clients using only one implementat ...

Extracting IDs, classes, and elements from a DOM node and converting it into a string format

Can someone please guide me on how to extract the DOM tree string from an element? Let's consider this HTML structure: <div> <ul id="unordered"> <li class="list item">Some Content</li> </u ...

Fill in the select dropdown menu

I am trying to trigger the population of a select dropdown when the user clicks on it. The issue I am facing is that the click handler seems to be activated only when the user clicks on the options within the select, whereas in my case there are no optio ...

Mocking a named class-export in TypeScript using Jest

I have a node module that exports several classes, including one called Client, which I utilize to create clients with various APIs as methods. I'm currently attempting to test my module, which has a dependency on this node module, using Jest. Howeve ...

Finding the main directory in JavaScript: a step-by-step guide

My website uses mod_rewrite to reformat the URLs like this: The issue arises when making AJAX calls to a file: I want to access login.php from the root without specifying the full URL or using the "../" method due to varying folder levels. So, I need a ...

What is the best way to encode a JSON object using Jquery Week Calendar under the subject "JSON parsing"?

I am currently utilizing Week Calendar (https://github.com/themouette/jquery-week-calendar/wiki) in my ruby on rails project. However, I am encountering an issue with the JSON object in my ruby code that is supposed to return JSON data to the weekcalendar. ...

What are the different ways to interact with the object retrieved from the onloadedmetadata event

Having trouble accessing a specific value in an object that is the result of the onloadedmetadata event. When I log the entire object using audioDuration, I am able to see and retrieve the respective value without any issues. However, when I try to access ...

Tips to prevent redundancy in a one-line 'if' statement in JavaScript

While working on a piece of code, I came across something bothersome and couldn't find a solution even after doing some research. It's functional, but it feels redundant to have to type this.className three times: this.className != 'selecte ...

Using the HTMLTextAreaElement object in Vue.js

I'm utilizing the Laravel package "laracasts/utilities" to transmit Laravel variables to JavaScript files. Below is the code snippet from my controller: JavaScript::put([ 'description' => $room->description ]); He ...

Verifying form input with jQuery's range validation

Is there a way to validate a field within a specific range? I have been using additional-methods for validation, but I am unsure of how to specify the range parameter in my HTML. For example: <input type="text" class="rangeField" rel="[10, 20]" /> ...

What is the best way to replicate a synchronous ajax call? (mimicking synchronous behavior with asynchronous methods)

Given that a "native" synchronous ajax call can block the user interface of the browser, it may not be suitable for many real-world scenarios (including mine). I am curious to know if there is a way to mimic a synchronous (blocking) ajax call using an asy ...

What is the best method to set the size of an array in a C library?

Currently, I am in the process of developing a C library that consists of both .h and .c files for a ring buffer. The goal is to be able to initialize this ring buffer library within the main project by calling something like ringbuff_init(int buff_size);, ...

Display bootstrap modal hyperlink in web browser search bar

Utilizing bootstrap cards with href tags allows users to click on them and open bootstrap modals. I want users to be able to copy the modal's URL link for sharing purposes, but the issue is that when the modal is opened, the URL remains unchanged. How ...