Home > database >  Javascript - How using a variable for object property
Javascript - How using a variable for object property

Time:12-05

Im very beginner in javascript, i would like to use all variable created on each object property :

let title = "Les Miserables";
let resume = "Blabla blaaabla...";
let autor = "Victor Hugo"
let date = "1862"

const books = {
        title: title,
        resume: desc,
        autor: autor,
        date: date,
      }

I want a result like this =>

{ title:'Les Miserables', resume:'Blabla blaaabla...', autor:'Victor Hugo', date: '1862'}

Is this possible ?

CodePudding user response:

You can use object property shorthand notation:

let title = "Les Miserables";
let resume = "Blabla blaaabla...";
let autor = "Victor Hugo";
let date = "1862";

const books = {
  title,
  resume,
  autor,
  date,
};

console.log(books); /* Logs:
{
  title: "Les Miserables",
  resume: "Blabla blaaabla...",
  autor: "Victor Hugo",
  date: "1862"
} */

You can also assign the values directly to properties on the object instead of first declaring individual variables in the scope:

const books = {};

books.title = "Les Miserables";
books.resume = "Blabla blaaabla...";
books.autor = "Victor Hugo";
books.date = "1862";

console.log(books); /* Logs:
{
  title: "Les Miserables",
  resume: "Blabla blaaabla...",
  autor: "Victor Hugo",
  date: "1862"
} */

  • Related