What is the most efficient way to assign multiple keys and values to an object in JavaScript using a function?

I possess an object

var bar = {
    "propA" : "valueX",
    "propB" : "valueY",
    "propC" : "valueZ"
};

and I am looking for a method to create a function that can receive multiple key and value pairs all at once.

My current approach is as follows:

function addPropAndVal(){
    for (var j = 0; j < arguments.length; j++) {
        bar[arguments[j]] = [arguments[j + 1]];
    }
}

Does this seem correct?

Answer №1

You're almost there! Just remember to adjust the loop by adding 2 to 'i' and remove the brackets around the value in the assignment line. This will prevent the value from being treated as an array, which is not what we want.

Updated code:

var foo = {
    "prop1" : "value2",
    "prop2" : "value3",
    "prop3" : "value4"
};

function propAndValAdder(){
    for (var i = 0; i < arguments.length; i+=2) {
        foo[arguments[i]] = arguments[i + 1];
    }
}

propAndValAdder("prop4","value5","prop5","value6");
console.log(foo);

// Object { prop1: "value2", prop2: "value3", prop3: "value4", prop4: "value4", prop5: "value6" }

Answer №2

You need to provide your details as parameters and resolve the issue in your loop.

Improved version:

   /**
 * Set properties and values for the specified object
 * @param  {array} arguments An array containing alternating keys and values
 * @param  {object} obj       [null] The object to set properties on
 * @return {obj}           Return the object, although not necessary since it's an object (references)
 */
function propAndValAdder(arguments,obj) {
    if (!obj) obj = {};
    if (arguments.join) //Make sure it is an array
        for (var i = 0; i < arguments.length; i += 2)
        obj[arguments[i]] = arguments[i + 1];
    return obj;
}

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

How can I determine if my clients are utilizing the CDN or NPM versions of my JavaScript library?

At this moment, I'm contemplating releasing an open-source version of my library on NPM. My main concern is figuring out how to track the usage of my CDN or NPM by clients. Is there a method available to achieve this? ...

Blank YouTube Popup Modal

I am in the process of creating a pop-up modal that contains an embedded YouTube video, but my modal is not displaying properly. I am utilizing Bootstrap and have two separate sections along with JavaScript code. When the modal appears, it remains empty. I ...

The state may be modified, but the component remains unchanged

I've been tasked with implementing a feature on a specific website. The website has a function for asynchronously retrieving data (tickets), and I need to add a sorting option. The sorting process occurs on the server side, and when a user clicks a s ...

Having trouble retrieving the input value using JavaScript

I have been attempting to retrieve the value of an input tag using JavaScript and display it on the console, but my code seems to be not functioning properly. Can someone help me identify the issue in the following code snippet? const userTextValue = doc ...

Error VM5601:2 encountered - Unexpected token "<" found in JSON at position 10

I am trying to retrieve data using Ajax and jQuery, but I keep encountering an error that I cannot figure out how to fix. VM5601:2 Uncaught SyntaxError: Unexpected token < in JSON at position 10 Below is the code I am working with. Model public f ...

Unable to access the response received from subscribing in Angular

I came across a helpful guide on this website, and I attempted to implement a similar concept discussed in the section about Unrelated Components: Sharing Data with a Service. Data Service: @Injectable() export class MyDataService{ private messageSou ...

What is the best way to set the state to false upon unmounting a component in react?

Currently, I am controlling the state of a dialog using context. Initially, the isOpen state is set to false. When the add button is clicked, the state isOpen becomes true and clicking the cancel button will revert it back to false. If the user does not c ...

Implementing a Standardized Template for Consistent Design and styling Throughout Website

As I work on building my website, I find myself struggling with some of the intricacies. The homepage is set up with a navbar and header, along with several pages that can be easily navigated to. While everything seems to be functioning properly, upon ins ...

The issue with CSS filter invert not functioning properly in Mozilla Firefox is causing complications

I am currently developing a small Firefox add-on designed to make reading pages at night more comfortable. The goal is to invert page colors without affecting images. Here is the code snippet I am using: document.body.style.filter = "invert(100%)"; var i ...

Revealing elements with AngularJS ng-show directive prior to concealing them

Currently, I am in the process of implementing a slide effect for bootstrap badges to showcase hierarchical data relationships using AngularJS. My goal is to have a slider-effect that smoothly reveals new sub-categories while concealing previously open su ...

JS Tips for using the .push() function with Multidimensional Arrays in JavaScript

After coming across this code example online, I decided to give it a try. The code snippet involved using the JavaScript array push method to add new elements to an inner sub-array, which was exactly what I needed to achieve! The code successfully demons ...

Guide to verifying Regular Expressions for text fields in JSP with JavaScript

Need help with validating the firstname using regex. The javascript code provided generates an error if the value length is 0, however, even after entering a correct firstname format based on the regex, it still shows 'First name invalid'. I susp ...

Avoiding URL images on 404 errors in frontend applications

My goal is to dynamically implement images (from image_url_1.jpg to image_url_5.jpg) based on a specific URL. While everything works fine, I encounter an issue when a particular image, like "image_url_4.jpg," is not available and results in a 404 Error cau ...

Ways to initialize Nested Arrays in Angular applications

I have been experimenting with some code on Codepen. I am trying to load JSON data from a service and then use ng-repeat to display the arrays. The issue I'm facing is that while the first array loads successfully, the nested array "data.cities" is n ...

Guide to concealing List elements from the Search Filter when the search input field is emptied

I am facing a challenge with an HTML list of items. Here is the structure: <ul id="fruits"> <li><a href="#">Mango</a></li> <li><a href="#">Apple</a></li> <li><a href="#">Grape</a>& ...

Creating a pie chart with ExtJS using data from a JSON file

After successfully creating a pie chart using ExtJS with JSON values through AJAX calling, I encountered an issue when trying to do the same with JSON values retrieved from a file named myjson.json. Can anyone advise me on how to draw a pie chart by retrie ...

The image you are looking for at './expo-asset/assets/${your_img_path}' was not located within React Native or Expo

My current project is an expo ejected react native project and I'm encountering the error message [native] Could not find image on path The file path in question: 'file:///var/mobile/Containers/Data/Application/..../Library/Application%20Support ...

Revolutionary scroll-based navigation fill transition

I'm attempting to achieve an effect where the fill color of the "insticon" SVG changes from black to white based on the scroll position indicated in the jQuery code. I have made the necessary modifications in the if and else statements, but unlike "he ...

transform json array into a consolidated array by merging identical IDs

I need to transform an array into a different format based on the values of the ID and class properties. Here is the initial array: const json = [{ "ID": 10, "Sum": 860, "class": "K", }, { "ID": 10, "Sum": 760, "class": "one", }, { "ID": ...

Is it possible to modify the CSS styles for a specific portion of an input value?

Currently, I am in the process of developing a form using React.js where a specific input must match the label written above it. Here is an example: https://i.stack.imgur.com/S2wOV.png If there happens to be a typo, the text should turn red like this: h ...