Jawadovic3814
Jawadovic3814

Reputation: 407

JavaScript: how to add new element to an object?

I have a 'this.captions' object in JavaScript and I want to add other elements to my object, how can I do this?

<script>
    this.captions = {
        c125: {
            fr: "TÉLÉPHONE",
            en: "PHONE NUMBER"
        },
        c126: {
            fr: "COMMENTAIRE",
            en: "COMMENT"
        }
    };
    var c50 = [];
    c50.push({fr:"NOM", en:"NAME"});
    console.log(this.captions.c126.fr); //COMMENTAIRE

    var dataFr = "Ville";
    var dataEn = "City";
    var id = 70;

    this.captions.c + id = {
        fr: dataFr,
        en: dataEn
    }

</script>

I have this error: 'Uncaught ReferenceError: Invalid left-hand side in assignment'

Upvotes: 0

Views: 49

Answers (2)

Mati
Mati

Reputation: 1148

You can add new properties to an existing object by simply giving it a value:

this.captions = {
  c125: {
    fr: "TÉLÉPHONE",
    en: "PHONE NUMBER"
  },
  c126: {
    fr: "COMMENTAIRE",
    en: "COMMENT"
  }
};

this.captions.c50 = {
  fr: 'NOM',
  en: 'NAME'
}

console.log(this.captions);

Upvotes: 2

jjislam
jjislam

Reputation: 563

by more elements, do you mean properties? you can add properties by either:

adding another like so:

c123:{
    fr:...
    en:...
}

or

this.caption.c123 = "fr...";

Upvotes: 0

Related Questions