-1

My scenario is like this :

var data = { 
    name : 'joe',
    message : 'Welcome ' + name,
    fullname : 'Mr. ' + name
};

Expected Output :

console.log(' user : ' + data.message)
Welcome joe

How to do this ?

uday214125
  • 569
  • 1
  • 8
  • 22
  • Voting to close as your question is unclear. `message : 'Welcome ' + name,` is invalid unless you have declared `name` beforehand. – Ivan Jun 12 '18 at 21:11

6 Answers6

3

The probably closest approach would be to use functions as parameters.

const data = {
   name: 'Joe',
   message: function() {
      return `Welcome ${this.name}`;
   }
}

console.log(data.message())

However, keep in mind that this does not work for native JSON objects, only for JS objects.

Ivan
  • 34,531
  • 8
  • 55
  • 100
Lukas Bach
  • 3,559
  • 2
  • 27
  • 31
  • I originally wanted to use the ${} syntax, but decided not to because the author used string concatenation. It doesn't really matter in this scenario if backticks or "/' are used anyway. – Lukas Bach Jun 12 '18 at 21:15
  • @Ivan They are called [`Template Literals`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals). It was introduced in `ES6`. – Alex Jun 12 '18 at 21:15
  • @LukasBach, yes, Its correct , its working fine , it wanted like this only. Thanks – uday214125 Jun 12 '18 at 21:18
  • Yeah @Ivan they are – Alex Jun 12 '18 at 21:19
2

You can define a function getter inside an object using get() and then call it as a property.

var data = { 
  name : 'joe',
  message : 'Welcome ',
  name : 'Mr. ',
  get fullMessage() {
    return this.message + this.name;
  }
};

console.log(data.fullMessage);
Ivan
  • 34,531
  • 8
  • 55
  • 100
Alex
  • 2,164
  • 1
  • 9
  • 27
0

You can replace message and fullname string by functions like this :

var data = { 
    name : 'joe',
    message : function() { return 'Welcome ' + this.name },
    fullname : function() { return 'Mr. ' + this.name }
}

console.log(data.message())
console.log(data.fullname())
0

If you want to do it in the initialization of the variable, you can do it using functions. Example:

var data = { 
    name : 'joe',
    message: function(){
     return 'Welcome ' + this.name;
    },
    fullname: function(){
     return 'Mr. ' + this.name;
    }
}

console.log('user : ' + data.message());
console.log('user : ' + data.fullname());
0

You could use getters:

var data = { 
    name : 'joe',
    get message() { return `Welcome ${this.name}`; },
    get fullname() { return `Mr. ${this.name}`; },
};

console.log(data.message);
console.log(data.fullname);
Hitmands
  • 13,491
  • 4
  • 34
  • 69
-1

You can use external variable of your jSON object. Try :

var name = "joe";
var data = { 
        name : name,
        message : 'Welcome ' + name,
        fullname : 'Mr. ' + name
    };
    
console.log(' user : ' + data.message);
Chris
  • 234
  • 3
  • 16