Reputation: 75127
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:
type is an object that has field:
So I one that:
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"
Upvotes: 2
Views: 8169
Reputation: 4160
I 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 accomplish...
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
Upvotes: 4
Reputation: 169383
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;
}
Upvotes: -1