Home > Back-end >  how can I use an object property name as a function parameter
how can I use an object property name as a function parameter

Time:08-27

Goal: I'm trying to create a simple function which checks if a property exists in an object, if it doesn't, the property is then created and the value is assigned to it. Problem: the parameter from the function parameters is not being read.

let b = {
  name: 'Chuck Berry',
  job: 'musician',
  bestTune: 'Johnny Be Good',
};

const propertyChecker = (obj, property) => {
  obj.property = obj.property || 'American';
  console.log(obj);
};

propertyChecker(b, 'nationality');

console.log: {name: 'Chuck Berry', job: 'musician', bestTune: 'Johnny Be Good', property: 'American'} bestTune: "Johnny Be Good" job: "musician" name: "Chuck Berry" property: "American" ---- this should be (nationality: "American")

CodePudding user response:

In JavaScript, there are 2 ways to access a property of an object:

  1. dot notaion: obj.property;
  2. brackets notation: obj['property'];

If the property is stored in a variable, you can only use the brackets notaion.

You need to change this line:

obj.property = obj.property || 'American';

to:

obj[property] = obj.[property] || 'American';

because property is a variable.

  • Related