2

I am trying to add parameters to a function in javascript, but it doesnt work somehow.

Can you let me know, how can I add them ?

I have a function like :

var foo = function () {
        var a = {
            "abc":"value1"
            "bcd":"value2"
        }
        return a;
    };

Now, I do this :

alert(data: [foo()]) // Actually I keep it in my function and **it works**

And I can see "abcd" and "bcd" with values.

But, Now I want to add a more variable (which is dynamic), how can I do that

I try this :

data:[foo() + {"cde":"value3"}] //doesnt work
data:[foo().push ({"cde"="value3"})] //doesnt work

How can I add a more variable to this array

1
  • Even if you are creating a C# application, if your question isn't related to C#, there's no benefit to tagging it. Commented Nov 14, 2016 at 20:20

3 Answers 3

4

The foo is a function that returns an object not an array. So there isn't any push method. If you want to add a new property to the object that foo returns you can do so as below:

// keep a reference to the object that foo returns
var obj = foo();
obj["cde"] = "value3";

or using dot notation as

obj.cde = "value3";

var foo = function () {
    var a = {
        "abc":"value1",
        "bcd":"value2"
    }
    return a;
};

var obj = foo();
obj["cde"] = "value3";

console.log(obj);

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

Comments

1

Why not try as below:

var x = foo();
x["newProp"] = 33;

2 Comments

Any reason they couldn't do x.newProp = 33?
@musicnothing Yes, that's also possible.
0

You can use rest parameter, spread element Object.assign() to return a if no parameters passed, else set passed parameters to a object

var foo = function foo(...props) {
  var a = {
    "abc": "value1",
    "bcd": "value2"
  }
  // if no parameters passed return `a`
  if (!props.length) return a;
  // else set passed property at `a` object
  return Object.assign(a, ...props);
};

var a = foo();
var b = foo({"cde":"value3"});
console.log(a, b);

Comments

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.