Home > Net >  Using push inside a function on object that I call
Using push inside a function on object that I call

Time:11-05

I am trying to push a string into an array, I have multiple arrays inside properties. I want to choose what property I am pushing it into using a function call but I can't seem to do it.

var aObj = {
 prop5: ["nameA5.1", "nameA5.2"],
 prop6: ["nameA6.1", "nameA6.2"]
};

function func (propX, namn) {
  var asd = aObj.prop5.push(namn);
  return aObj;
};
console.log(func("","test text"));

This code above works but not like I want it to. Now I can only push something into the property named "prop5, I want to choose what object when I call my function.

I tried to just change this:

var asd = aObj.prop5.push(namn);

to this:

var asd = aObj.propX.push(namn);

So whenever I call the "propX" I can choose what object I am calling,but I couldn't do that.

I get the error "TypeError: Cannot read properties of undefined (reading 'push')"

CodePudding user response:

For using a variable as an object key you have to use bracket [] notation. Simply change aObj.propX.push(namn) to aObj[propX].push(namn)

var aObj = {
  prop5: ["nameA5.1", "nameA5.2"],
  prop6: ["nameA6.1", "nameA6.2"]
};

function func (propX, namn) {
  var asd = aObj[propX].push(namn);
  return aObj;
};
console.log(func("prop5","test text"));

CodePudding user response:

Additional to @Axekan you need to check if the property exists first, if not assign it to an empty array with aObj[propX] ??= [].

let aObj = {
 prop5: ["nameA5.1", "nameA5.2"],
 prop6: ["nameA6.1", "nameA6.2"]
};

function func (propX, name) {
  aObj[propX] ??= []
  aObj[propX].push(name)
  return aObj;
};
func("prop5","test text")
func("prop1","test text")

console.log(aObj)

  • Related