Reputation: 8033
I have a set of nesting json object like this:
var obj = {
name: "student",
contact: {
phone: "22222",
fax: "33333",
...
},
...
}
And I have these text fields:
<input type="text" name="name" />
<input type="text" name="contact_phone" />
<input type="text" name="contact_fax" />
...
Now I want to fill these fields with appropriate property from above object. My question is how can I access anonymous property from that object? For example suppose I have this jquery code:
$("#formID").find("input").each(function(index) {
fieldName = $(this).attr("name");
var namePart = fieldName.split("_");
//I want something like this: console.log(obj.namePart[0].namePart[1])
});
Upvotes: 0
Views: 136
Reputation: 2166
Edit: Sorry about that I misunderstood the question. What you are looking for is something like this.
var obj = {
name: "student",
contact: {
phone: "22222",
fax: "33333"
}
};
$('#formID').("input").each(function(index) {
fieldName = $(this).attr("name");
var namePart = fieldName.split("_");
var arbitraryVal = obj;
for (var part in namePart) {
if (arbitraryVal.hasOwnProperty(namePart[part])) {
arbitraryVal = arbitraryVal[namePart[part]];
continue;
}
arbitraryVal = null;
break;
}
if (typeof $(this).val(arbitraryVal) !== 'undefined') {
$(this).val(arbitraryVal);
}
});
recusivly searches an object for each name part. If the name part is
contact_phone
It will look for obj.contact.phone
if it is something_else_with_lots_of_underscores
it will look for obj.something.else.with.lots.of.underscores
Upvotes: 0
Reputation: 430
<form ID="formID">
<input type="text" name="name" />
<input type="text" name="contact_phone" />
<input type="text" name="contact_fax" />
</form>
$("#formID").find("input").each(function() {
fieldName = $(this).attr("name");
namePart = fieldName.split("_");
if(namePart.length ==1 && namePart[0]=="name"){
$(this).val(obj.name);
}
else if(namePart.length>1){
$(this).val(obj[namePart[0]][namePart[1]]);
}
//I want something like this: console.log(obj.namePart[0].namePart[1])
});
Upvotes: 0
Reputation: 20636
Use obj["propertyName"]
obj[namePart[0]][namePart[1]]
$('#formID').find("input").each(function(index) {
fieldName = $(this).attr("name");
var namePart;
if(fieldName.indexOf('_') > -1){
namePart = fieldName.split("_");
console.log(obj[namePart[0]][namePart[1]])
}
else{
namePart = fieldName;
console.log(obj[namePart])
}
});
*Note: The property is not anonymous. If your run obj["propertyName"]
on an object with no such property it will return undefined.
Upvotes: 3