1

For example:

var myObject = {
 name : 'David',
 age: '30,
 salary:'30000'
}

I need answers like: My name is David, I'm 30 years old. I earned monthly 30000.

Note: Without using '.' DOT operator and for and foreach.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Bharath-CODER
  • 392
  • 1
  • 3
  • 13

3 Answers3

3

This should work:

var myObject = {
    'name' : 'David',
    'age': '30',
    'salary':'30000'
 };
console.log('My name is '+myObject['name']);

Here is the JSFiddle Example: Link

Karthikcbe
  • 295
  • 2
  • 12
Roy Christo
  • 354
  • 2
  • 13
  • `['key']` would be equivalent to `.key` so I don't know how this bypasses the "no dot" requirement of OP. Something is a bit off here – apokryfos Sep 29 '22 at 06:41
  • object.key and object[key] accomplish the same thing. However, object.key only works if the key name is hardwired ( I mean not happening dynamically since it cannot change at run-time). It also does not work when the key is a number instead of a string. In other words, object[key] is more versatile. https://www.codecademy.com/forum_questions/54c30d4195e378bd8900045b#:~:text=key%20and%20object%5Bkey%5D%20accomplish,number%20instead%20of%20a%20string. [https://stackoverflow.com/questions/62481352/difference-between-object-key-and-objectkey-in-for-loop-in-javascript](Difference) – Roy Christo Sep 29 '22 at 06:50
  • Yes I am aware of that however **here** in this particular case the key **is** hardwired making this syntax less readable. – apokryfos Sep 29 '22 at 08:21
2

var myObject = { name : 'David', age: '30', salary:'30000' } //object destructure

let {name, age, salary} = myObject;

console.log(my name is ${name})

-1
var myObject = {
    'name' : 'David',
    'age': '30',
    'salary':'30000'
 };
console.log(`My name is ${myObject["name"]}, I'm ${myObject["age"]} years old. I earned monthly ${myObject['salary']}.`);