0
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.

4
  • 5
    But whatever I tried it's not working Post it and let us help you... Commented Sep 1, 2017 at 15:07
  • 1
    Did you try dictionary.val1.push("arr7") Commented Sep 1, 2017 at 15:07
  • from what you've posted: dictionary.val1.push("arra7") and dictionary.val3 = addNew (not AddNew) should do what you want. Commented Sep 1, 2017 at 15:07
  • Should be a simple push or concat. Commented Sep 1, 2017 at 15:07

4 Answers 4

3

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");

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

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

Comments

2

Do it like this:

dictionary.val1.push("arr7");

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

1 Comment

Worked perfectly, thank you so much, my friend. As I told I am new and sorry for taking your time.
0

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);

Comments

0

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

3 Comments

This was exactly what I need. Thanks.
Uncaught ReferenceError: PropertyName is not defined - be careful with case. It's also a bit pointless to wrap a basic language feature (obj[prop] = val) into a function.
Yes, I wrote that from directly here, typo;) He asked for a function that does that I delivered. I didn't question was it a good point to do so.

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.