goktanehrlich
goktanehrlich

Reputation: 1

How to add value in an array with function

var dictionary = {"val1": ["arr1", "arr2"], "val2": ["arr3", "arr4"]}

var addNew = ["arr5", "arr6"]
dictionary["Val3"] = AddNew

I would like to write a function to add another arr value into an array. For example: "val1": ["arr1", "arr2", "arr7]

But whatever I tried it's not working. I am new and I hope somebody can help me.

Upvotes: 0

Views: 82

Answers (4)

Ricardo diaz
Ricardo diaz

Reputation: 41

You can use this for add a property to the object

var dictionary = {
"val1": ["arr1", "arr2"], 
"val2": ["arr3", "arr4"]
}
var add =  function(prop, arr){
dictionary[prop].push(arr);

}

add("val2", "arr5");

/////////////////////////////

Upvotes: 3

CodeSmith
CodeSmith

Reputation: 3197

If I guessed right what you wanna add an array under new PROPERTY of OBJECT, not into ARRAY

function (targetObject, propertyName, newArray){
    targetObject[propertyName] = newArray;
}

Or you wanna add inside existing PROPERTY of OBJECT?

function(targetObject, targetProperty, newArrayToAdd){
    Array.concat[targetObject[targetProperty], newArrayToAdd]    
}

Upvotes: 0

Karl Reid
Karl Reid

Reputation: 2217

You could use the concat function to add new elements to the end of the relevant array :

var dictionary = {"val1": ["arr1", "arr2"], "val2": ["arr3", "arr4"]}

var addNew = ["arr5", "arr6"]
dictionary["val1"] = dictionary["val1"].concat(addNew);

Upvotes: 0

Sebastian Simon
Sebastian Simon

Reputation: 19475

Do it like this:

dictionary.val1.push("arr7");

addNew is not AddNew; val3 is not Val3. JavaScript is case-sensitive.

Upvotes: 2

Related Questions