简体   繁体   中英

Using variables as keys in multidimensional object

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.

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!

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/" } }

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

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

    var items = {};

    items[id] = obj;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM