1

I've created an array of object and in some of these objects I need to refer to the properties of that object inside of it like this:

let fields = [

{
    "ATTRIBUTE_NAME": "PERSON_NAME",
    "FIELD_NAME": "name"
    "ATTRIBUTE_ID": 1,
    "RULES": [
        {
            "MSG":`${this.ATTRIBUTE_NAME} is not valid`,
            "NAME": "VALID_VALUES",
        }
    ]
},
{
    "ATTRIBUTE_NAME": "PERSON_JOB",
    "FIELD_NAME": "job"
    "ATTRIBUTE_ID": 2,
    "RULES": [
        {
            "MSG":`${this.ATTRIBUTE_NAME} is not valid`,
            "NAME": "VALID_VALUES",
        }
    ]
}

] But this keyword returning undefined! I want the "MSG" property to pick up the attribute name and populate it for me. Does anybody know how to capture it inside the template string?

Nisman
  • 1,271
  • 2
  • 26
  • 56

2 Answers2

1

The easiest way would be to use a getter for your RULES property.

A simple demonstration:

var obj = {
  id: 1,

  get info() {
    return `The id is ${this.id}.`;
  }

}

console.log(obj.info);

Applied to your code:

let fields = [{
  "ATTRIBUTE_NAME": "PERSON_NAME",
  "FIELD_NAME": "name",
  "ATTRIBUTE_ID": 1,

  get RULES() {
    return [{
      "MSG": `${this.ATTRIBUTE_NAME} is not valid`,
      "NAME": "VALID_VALUES",
    }]
  }

}];

console.log(fields[0].RULES[0].MSG);
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
0

You can't use a self-reference like that, because the fields array and its sub-elements have not yet been declared. What you can do, instead, is:

  1. Declare the fields array and its sub-elements first.
  2. Then, iterate over every element and add the object you want in the RULES array.

Example:

/* Declare the array and its sub-elements. */
let fields = [{
    "ATTRIBUTE_NAME": "PERSON_NAME",
    "FIELD_NAME": "name",
    "ATTRIBUTE_ID": 1,
    "RULES": []
  },
  {
    "ATTRIBUTE_NAME": "PERSON_JOB",
    "FIELD_NAME": "job",
    "ATTRIBUTE_ID": 2,
    "RULES": []
  }
];

/* Iterate over every element. */
fields.forEach(element => {
  element.RULES.push({
    "MSG": element.ATTRIBUTE_NAME + " is not valid",
    "NAME": "VALID_VALUES"
  });
});

/* Log the result. */
console.log(fields);
Angel Politis
  • 10,955
  • 14
  • 48
  • 66