2

I am working on a controller that takes an sObject record and finds the values of a list of field names on an Asset:

for (var fid in fsNamesList) {
    var fieldname = fid;
    var fieldvalue = sobjectrecord[fid];
}

This works well with fid = 'Name', but it falls apart when the field refers to a parent object, such as (Asset).Contact.LastName.

I tested with explicit references, and Asset[Name] works, while Asset[Contact.LastName] does not.

Does anyone have a workaround?

1 Answer 1

2

Objects are "nested" within each other when you speak of parent-child relationships. For example, given Contact.LastName, your object looks like this:

{ Name: "My Asset", Contact: { LastName: "Fear" } }

Which means you have to navigate through the path. Hard-coded, it would look like this:

sobjectrecord['Contact']['LastName']

Dynamically speaking, you can simply follow the path:

function fieldValue(record, fieldPath) {
    var path = fieldPath.split(/\./), temp = record;
    while(path.length) temp = temp[path.shift()];
    return temp;
}

(You could also use forEach or another method; this was meant primarily to be demonstrative).

2
  • Thanks! I hadn't thought of that technique. I'll try it today and will mark the answer if I can get it to work. Commented Jan 28, 2016 at 20:00
  • Yup - that got me on my way. I didn't make it quite that extensible to use shift, but I did do a check in the string for '\' and then did the split and returned sobjectrecord[path[0]][path[1]], which did the trick. Commented Jan 28, 2016 at 22:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .