I have an object and some of its elements are object too. How can I make my variable just one object?
I mean I have a variable that has elements:
- name
- type
type is an object that has field:
- name
So I one that:
- name
- type.name (not as an object just another variable as like name)
PS: When I inspect my variable with Firebug:
name
"fsfaf"
password
"242342425"
name
"XXX"
type
Object { name="sds"}
name
"sfs"
Let's assume that I hold it with a variable myVariable
. I want to do something like that:
var newVariable = somefunction(myVariable);
so my newVariable should be like that:
name
"fsfaf"
password
"242342425"
name
"XXX"
type.name
"sds"
name
"sfs"
I have an object and some of its elements are object too. How can I make my variable just one object?
I mean I have a variable that has elements:
- name
- type
type is an object that has field:
- name
So I one that:
- name
- type.name (not as an object just another variable as like name)
PS: When I inspect my variable with Firebug:
name
"fsfaf"
password
"242342425"
name
"XXX"
type
Object { name="sds"}
name
"sfs"
Let's assume that I hold it with a variable myVariable
. I want to do something like that:
var newVariable = somefunction(myVariable);
so my newVariable should be like that:
name
"fsfaf"
password
"242342425"
name
"XXX"
type.name
"sds"
name
"sfs"
Share
Improve this question
edited Oct 31, 2011 at 12:04
kamaci
asked Oct 31, 2011 at 11:46
kamacikamaci
75.4k73 gold badges245 silver badges372 bronze badges
2
-
Why do you want to do this? Btw, if you have
type.name
type is a still an object! – Richard Dalton Commented Oct 31, 2011 at 12:03 - I want a new element instead of type, type.name. type.name is not an object(I tested with Firebug what I want to do, type.name doesn't seem as an object) – kamaci Commented Oct 31, 2011 at 12:07
2 Answers
Reset to default 4I edited my answer too. Here's a way to do what you want:
var myVar =
{
name: 'myName',
type: { name: 'type.name' }
}
function varToNewVar(myVar)
{
var newVar = {};
for(var i in myVar)
{
if(typeof myVar[i] === 'object')
{
for(var j in myVar[i])
{
newVar[i+'.'+j] = myVar[i][j];
}
}
else
newVar[i] = myVar[i];
}
return newVar;
}
var newVar = varToNewVar(myVar);
However, this way you cannot access newVar.type.name, you can access newVar['type.name'], which I guess is OK for what you want to acplish...
P.S. Test extensively before applying to live projects, etc. I imagine a lot of things can go wrong, depending on the objects that you're using. There should be no problem to use it in the situation you want though
var o = {
"name": "my_name",
"type.name": "type's name"
}
Seriously though, what? What do you actually want?
function IAmAUselessHack(o) {
o["type.name"] = o.type.name;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745537862a4631988.html
评论列表(0条)