0

I need help in how to add an array property to an object with given key where the input is

var myObj = {};
var myArray = [1, 3];

and the output should be like this:

addArrayProperty(myObj, 'myProperty', myArray);

console.log(myObj.myProperty); // --> [1, 3]

I built a code and it gives me the exact output but when changing the values it gets undefined!

  var myObj = {};
  var myArray = [1, 3];
  var myProperty = myArray;
function addArrayProperty(obj, key, arr) {
  myObj.myArray = myObj.myProperty;
  return myArray;
}
addArrayProperty(myObj, 'myProperty', myArray);

I believe that my code has something wrong can any one help? thanks in advance.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
Salma Elshahawy
  • 1,112
  • 2
  • 11
  • 21

1 Answers1

0

You should replace myObj.myArray = myObj.myProperty;

to myObj.myProperty = myObj.myArray;

var myObj = {};
var myArray = [1, 3];
function addArrayProperty(obj, key, arr) {
  myObj[key] = arr;
  return myObj;
}
addArrayProperty(myObj, 'myProperty', myArray);

console.log(myObj);
console.log(myObj.myProperty); // [1, 3]
Mohamed Abbas
  • 2,228
  • 1
  • 11
  • 19