Save Object Using Variable with Object Name

Save object using variable with object name

Try save(list=objectName, file=paste(objectName, '.Rdata', sep='') ).

The key is that the list argument to save takes a list of character strings that is the names of the objects to save (rather than the actual objects passed through ...).

Javascript use variable as object name

Global:

myObject = { value: 0 };
anObjectName = "myObject";
this[anObjectName].value++;

console.log(this[anObjectName]);

Global: v2

var anObjectName = "myObject";
this[anObjectName] = "myvalue"

console.log(myObject)

Local: v1

(function() {
var scope = this;

if (scope != arguments.callee) {
arguments.callee.call(arguments.callee);
return false;
}

scope.myObject = { value: 0 };
scope.anObjectName = "myObject";
scope[scope.anObjectName].value++;

console.log(scope.myObject.value);
})();

Local: v2

(function() {  
var scope = this;

scope.myObject = { value: 0 };
scope.anObjectName = "myObject";
scope[scope.anObjectName].value++;

console.log(scope.myObject.value);
}).call({});

create object using variables for property name

If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets:

var foo = "bar";
var ob = { [foo]: "something" }; // ob.bar === "something"

If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel):

Create the object first, and then add the property using square bracket notation.

var foo = "bar";
var ob = {};
ob[foo] = "something"; // === ob.bar = "something"

If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.

How do I assign a variable to an object name?

Instead of using a new variable for each customer you could store your object in a Python dictionary:

d = dict()

for record in result:
objectname = 'Customer' + str(record[0])
customername = str(record[1])
d[objectname] = Customer(customername)

print d

An example of objects stored in dictionaries

I just could'nt help my self writting some code (more than I set out to do). It's like addictive. Anyway, I would'nt use objects for this kind of work. I probably would use a sqlite database (could be saved in memory if you want). But this piece of code show you (hopefully) how you can use dictionaries to save objects with customer data in:

# Initiate customer dictionary
customers = dict()

class Customer:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
self.address = None
self.zip = None
self.state = None
self.city = None
self.phone = None

def add_address(self, address, zp, state, city):
self.address = address
self.zip = zp
self.state = state
self.city = city

def add_phone(self, number):
self.phone = number

# Observe that these functions are not belonging to the class.
def _print_layout(object):
print object.fname, object.lname
print '==========================='
print 'ADDRESS:'
print object.address
print object.zip
print object.state
print object.city
print '\nPHONE:'
print object.phone
print '\n'

def print_customer(customer_name):
_print_layout(customers[customer_name])

def print_customers():
for customer_name in customers.iterkeys():
_print_layout(customers[customer_name])

if __name__ == '__main__':
# Add some customers to dictionary:
customers['Steve'] = Customer('Steve', 'Jobs')
customers['Niclas'] = Customer('Niclas', 'Nilsson')
# Add some more data
customers['Niclas'].add_address('Some road', '12312', 'WeDon\'tHaveStates', 'Hultsfred')
customers['Steve'].add_phone('123-543 234')

# Search one customer and print him
print 'Here are one customer searched:'
print 'ooooooooooooooooooooooooooooooo'
print_customer('Niclas')

# Print all the customers nicely
print '\n\nHere are all customers'
print 'oooooooooooooooooooooo'
print_customers()

How to define a java object name with a variable?

Your choice of words shows that you don't fully understand the way variables and objects work, and you need to fix that to get anywhere with Java.

If I write:

Item myItem = new Item();

I create a new object, and I define a variable which points to that object.

The object does not have a name (it has an ID, which is a number assigned at runtime; most programmers can ignore it).

The variable has a name, myItem. The variable points to the object. Later on, it might point to a different object. The variable might fall out of scope and cease to exist, while the object continues to exist.

You might say, "that's not important. If I say the 'name of the object', I mean 'the name of the variable pointing to the object'."

But it is important, because lots of objects will be pointed to by more than one variable:

Item myItem = new Item();
Item yourItem = myItem;
// both variables point to the same object. Neither variable is "more" the
// owner of the object than the other.

... and lots of objects won't be pointed to directly by a variable.

myList.append(new Item()); 
// you can't get at this new object using a direct variable.

In Java (and most mainstream languages), you can't create variable names at runtime. The only variable names that exist, are ones that are literally in the source code.

So there's nothing that works like this:

int number = 1;
Cell cell$number = new Cell(); // can't be done!
Cell currentCell = cell1;

Nor can you access variables by name, based on runtime data. So there's nothing that works like this:

Cell cell1 = ...;
int number = 1;
Cell currentCell = cell$number; // can't be done!

This is a good thing because it lets the compiler validate certain things about your code.

In some languages you could possibly achieve something like this using eval() -- but you should run a mile from it!

This is a hint that if you're writing code like:

 Cell cell0 = new Cell(...);
Cell cell1 = new Cell(...);
...
Cell cell99 = new Cell(...);

... then you're doing something wrong. It may work, but it scales badly. There is no way to put this into a loop. (Don't worry - most of us hit this issue when we began programming).

If, instead you'd used an array:

 Cell[] cells = new Cell[];
cells[0] = new Cell(...);
cells[1] = new Cell(...);
...
cells[99] = new Cell(...);

Then you could use a loop instead:

 for(int i = 0; i<100; i++) {
cells[i] = new Cell(...);
}

An array is the simplest of "collection" objects. There are also Sets, Lists, Maps, and a host of more advanced collections, to suit most needs.

You seem to want to store and access objects using strings as a key. The way to do this is using a Map.

Map<String,Cell> myMap = new TreeMap<String,Cell>();

myMap.put("AA", new Cell(...));
myMap.put("AB", new Cell(...));

...

Cell currentCell = myMap.get("AA");

Map is an interface. TreeMap is just one class that provides an implementation of the Map interface. Read up on the various implementations of Map provided by the standard JRE.

The key doesn't have to be a String. Anything that implements equals() can be used as a key.

Using this:

for(char c = 'A'; c <= 'L'; c++) {
for(char d = 'A'; d<= 'L'; d++) {
myMap.put("" + c + d, new Cell(...));
}
}

However, since you've said you want a grid, it's probably better to work with a 2D array, and translate the numeric coordinates to and from a lettered grid-reference whenever you need to. Google for "2D array Java", and you'll find plenty of examples.

Cell[][] cells = new Cell[12][12];
for(int x=0; x<12; x++) {
for(int y=0; y<12; y++) {
Cell cell = new Cell();
cell.setName( "" + ('A' + x) + ('A' + y)); // perhaps
cells[x][y] = cell;
}
}

Beyond the standard JRE, there are plenty of other implementations of Map. For example, Spring provides DefaultRedisMap, in which the objects are stored in a Redis database.

More generally - you have asked a very basic question here. You should read the chapter on the Collections API in any decent Java book.

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};

obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2021:

Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.

const yourKeyVariable = "happyCount";
const someValueArray= [...];

const obj = {
[yourKeyVariable]: someValueArray,
}

Select a variable/object by it's name from many available with Javascript

JavaScript won't give you a list of declared variables and their names, so what you're trying to do won't work with plain variables unless you use eval like in Majed's answer, but I don't recommend that—using eval is generally discouraged because depending on your code it can open you up to security vulnerabilities.

What you could do instead is store JohnA and GeorgeA as properties on an object like so:

let names = {
JohnA: { countries: ... },
GeorgeA: { countries: ... }
}

and then you can programmatically access those properties:

let name = 'John';
names[name + 'A'].countries // ...


Related Topics



Leave a reply



Submit