1

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?

3
  • 1
    Object.defineProperties() Commented Jul 3, 2016 at 16:26
  • foo[arguments[i]] = [arguments[++i]]; Commented Jul 3, 2016 at 16:50
  • foo[arguments[i]] = arguments[++i]; (get rid of one set of []) Commented Jul 3, 2016 at 16:58

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

You should pass your information in the parameters and fix your loop.

Corrected version :

   /**
 * Add properties and values to the object
 * @param  {array} arguments An array where even are keys and odd are the values
 * @param  {object} obj       [null] The object to add properties
 * @return {obj}           Return the object but not nessary since it's an object(references)
 */
function propAndValAdder(arguments,obj) {
    if (!obj) obj = {};
    if (arguments.join) //We valid this is an array
        for (var i = 0; i < arguments.length; i += 2)
        obj[arguments[i]] = arguments[i + 1];
    return obj;
}

2 Comments

I think I would conceptually reverse the signature. Probably something more like foo(obj /*, args */) and then in the body capture the array of additional arguments with something like function var args = Array.from(arguments).slice(1)
You have to remove the []'s around [arguments[i + 1]]; or you end up assigning a one-element array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.