0

If I have some values and I want to store it as an object. So finally I need to call JSON.stringify() (because I am trying to store it in chrome extension)

var id = '1';
var name = 'Mali Bakery'
var url = 'http://example.com/'

So I thought the best thing would be sorting it like:

var items = {
     id : {
        'name': name,
        'url': url
     }
}

But I couldn't figure out how to put the variables inside the object template.

I tried using

item = {}
item[id] = id
item[id].name = name  
// etc

items.push(item);

// and also, this approach too
items.id = id

But no success.

senty
  • 12,385
  • 28
  • 130
  • 260

4 Answers4

2

You can put id in brackets [] so that it gets evaluated to the variables value:

var id = '1';
var name = 'Mali Bakery'
var url = 'http://example.com/'

var items = {
      [id] : {
        name,
        url
     }
}

console.log(items);

Note that you shouldn't use name as a variable's name!

baao
  • 71,625
  • 17
  • 143
  • 203
2

You could do this

var id = '1';
var name = 'Mali Bakery'
var url = 'http://example.com/'
var items = {}

items[id] = {
    'name': name,
    'url': url
}

console.log(items);

This gives the following output:

{ 1:{ name: "Mali Bakery", url: "http://example.com/" } }

lordvcs
  • 2,466
  • 3
  • 28
  • 37
1
var items = {};
items[id] = { name, url };
ideaboxer
  • 3,863
  • 8
  • 43
  • 62
1
    var id = '1';
    var name = 'Mali Bakery'
    var url = 'http://example.com/'

    var obj = {
            'name': name,
            'url': url
         }

    var items = {};

    items[id] = obj;
Prakash Sharma
  • 15,542
  • 6
  • 30
  • 37