Guide on updating dictionary values in Javascript

Is it correct that whenever the getVal function is called, a new dictionary should be created and its values replaced?

var dict = [];

    function getVal(inarr, element, data) {
        var arr = inarr[element].map((item) => item[data]);
        return arr;
    };

    console.log(getVal(event, 'foo', 'bar')); 

Answer №1

const retrieveData = (inputArray, element, info) => {
    let extractedData = inputArray[element].map((item) => item[info]);
    return extractedData;
};

console.log(retrieveData(event, 'foo', 'bar'));

Answer №2

Due to the lack of clarity in your query and missing input, any response will be a bit speculative. However, you might want to consider implementing something along these lines:

    // The 'keys' variable can be an array containing strings or functions.
    // If it's a function, it will receive the current object as an argument.
    function getMember(object, keys) {
        return keys.reduce(function(acc, key) {
            if (acc === undefined) {
                return acc;
            }
            if (typeof key === "function") {
                return key(acc);
            }
            return acc[key];
        }, object);
    }

    function getVal(object) {
        return getMember(object, [
            "foo", 
            function(x) {
                return x.map(function(x){
                    return x.bar; 
                });
            }
        ]);
    };

    var event = {
        foo: [
            { bar: 1 },
            { bar: 2 }
        ]
    };
    console.log(getVal(event)); // Output: [1, 2]

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

Instead of constantly updating my stateful component, I prefer to create a new paragraph for each new state

Each time the Create Sales Order Button is clicked, an API call is made and the response is printed as a Stateful Component. Rather than updating the existing component, I want to generate a new paragraph for each response received so that if the user clic ...

Can JQuery be used to detect text input in real-time in a textarea field?

Currently, I have a button for "post" that becomes active when text is typed into the text area. The issue arises when all text is deleted from the text area, as the button remains active in its coloured state despite being disabled using the following cod ...

Using AngularJS and the ng-show directive, you can set a <div> element to

Objective: My aim is to show the content of a div according to the status of checkboxes, while also ensuring that these divs are visible by default If I have this code snippet: <html> <head> <script src="https://ajax.googleapis.com/ajax/li ...

Minimizing Jitter in HTML5 and JavaScript Applications

I am currently working on developing a metronome as a hobby using JavaScript/HTML5 with the intention of turning it into a FirefoxOS app. One issue I've encountered is Jitter, which is unacceptable for Metronomes. As JavaScript is single-threaded and ...

Creating an interactive dropdown menu with simple_form

I am new to JS/Ajax and unsure how to render dynamic options based on previously inserted data in the same form. Background: The bike shop chain application allows the renting of bikes with names like "bike 1" or "yellow bike" ('bikes'), by sele ...

What is the process of creating and customizing popovers in Bootstrap 5 with jquery?

Is there a way to dynamically create and add content to Bootstrap 5 popovers using JavaScript or jQuery? In Bootstrap 3, I used the following method: $('#element').popover({ placement : 'left', trigger : 'focus', html: true } ...

What is the reason for receiving a JSX warning even though JSX is not being utilized in the code?

In my Vue.js component file using the Quasar framework, I have the following code block inside the <template>: <q-btn color="green" label="save & continue editing" @click="saveCase()" /> This snippet is par ...

Translating language in jquery date selector

Is there a way to combine language translation with changeMonth and changeYear options in jQuery datepicker? I have tried the following code: $(this).datepicker($.datepicker.regional['fr']); And for ChangeYear: $( this ).datepicker({ cha ...

What's the issue with this HTML button not functioning properly?

I'm having an issue with a button in my code that is supposed to change the text from 'hello' to 'Goodbye', but for some reason, it's not working. I have ensured that my code is properly indented in my coding program. Below i ...

Having trouble making Three.js with instancing work properly unless FrustumCulling is set to false

I've encountered an issue with three.js and instancing, similar to what others have experienced. The objects are randomly clipped and disappear from the camera view. Examples can be found here. Mesh suddenly disappears in three.js. Clipping? Three.j ...

Retrieve the ID from either a search query or an insertion operation in MongoDB

I find myself frequently using this particular pattern. It feels a bit cumbersome to make two MongoDB calls for the task, and I am curious if there is a more efficient way to achieve this. My goal is to obtain the ID of an existing document, or.. create ...

A shortcut for calling functions in Lodash

Looking to execute a series of functions using Lodash? Here's an example: const functions = [ () => console.log('Fn 1'), () => console.log('Fn 2') ]; _(functions).each(fn => fn()); Wondering if there is a Lodash ...

Guide on sending a JSON response from a POST request in JavaScript

After creating an API in Django that provides a JSON response based on a variable entered in the URL, I encountered a challenge with fetching and displaying this data using JavaScript. For instance, consider this URL: A sample of the JSON response looks ...

What is the best way to delete a particular item from a local storage array in AngularJS?

This is the HTML code I have: <tr ng-repeat="student in students track by $index"> //some code here <button ng-click="remove(student)">Delete</button> </td> </tr> Then, in my .js ...

Arrange files in the array based on their distance from the file path

I am currently working on organizing a list of file paths based on their proximity to the current file path. The code I have written so far is: filePaths .sort((a, b) => { const relativeA = path.relative(currentFilePath, a); const relati ...

Once the form is submitted, Vue automatically resets all the data

export default { data() { return { usrName: null, pass1: null, pass2: null, regState: {stateCode:-1}, } }, methods: { register: function () { this.axios.post("/login/", { baseURL: 'http://127 ...

Exploring the process of iterating through and organizing a JavaScript array

Recently, I encountered a JavaScript object that was generated by a particular API. The object is structured in a way that it can potentially have multiple instances of the same 'equity' (such as Hitachi Home in this case): { "results": { ...

Sending ng-model as an argument to a function along with another parameter, followed by resetting ng-model

This is an example of my HTML code: <input type="text" name="message" ng-model="senderMessage"> <button type="submit" ng-click="sendSenderMessage(1,5,senderMessage)"> Click Me </button> Here is my JavaScript controller function: $sc ...

Exploring the possibilities with Polymer and three.js

I've been attempting to integrate a three.js demo from http://jsfiddle.net/hfj7gm6t/ into my polymer app, but I'm encountering an error message: com-model-viewer.html:33 Uncaught TypeError: Cannot read property 'myview' of undefined ...

Saving Files in Your React Web Application: Tips and Tricks

Currently, I am working on a React web application that requires the temporary storage of Torrent pieces for streaming purposes using a web player. Any recommendations on how to properly store this data temporarily in order to facilitate the streaming pro ...