0

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'

5
  • 1
    this.captions.c50 = c50 Commented Dec 11, 2016 at 1:18
  • 1
    You don't want the c50 variable as an array. You want it as an object. So, var c50 = {fr:"NOM", en:"NAME"}; this.captions.c50 = c50; Commented Dec 11, 2016 at 1:24
  • See Objects Commented Dec 11, 2016 at 1:25
  • Thank you, but the result is not the same this.captions Object {c125: Object, c126: Object, c50: Array[1]} Commented Dec 11, 2016 at 1:27
  • Yes exactly thank you very much it works Commented Dec 11, 2016 at 1:29

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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...";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.