Antonio Ortiz Antonio Ortiz - 1 year ago 53
Javascript Question

How do I add multiple key and values to an object from a function in JavaScript?

I have an object

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


and i'd love a way to have a function which would allow one to input multiple key and value pairs at once.

Right now I have this:

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


Is this right?

Answer Source

You almost got it right: just have to change the loop to add 2 to 'i' (so that you don't add the value as another property, have to skip it) and get rid of the []'s around the value in the assignment line (this is making the value an array which we don't want).

Corrected 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" }