2017-05-28 22 views
0

我想能夠更新一個對象或幾個對象使用一個函數指定我想要在Obeject中更新的位置。我不確定它的正確語法。我的下面的嘗試實際上是在原始對象中創建一個新參數,相反,我想更新User對象的現有字段。你如何specfy對象的位置函數參數javascript

var User = { 
    local: { 
    location: { 
     city: "", 
     state: "" 
    } 
    } 
} 

var Profile = { 
    location: { 
    city: "", 
    state: "" 
    } 
} 

function update(model, parameter, updatedLocation) { 
     return model[updatedLocation] = { 
     city: updatedLocation.city, 
     state: updatedLocation.state, 
    }; 
} 

update(User, ["local"]["location"], { city: "ny", state: "ny"}); 
update(Profile, ["location"], { city: "ny", state: "ny"}); 

console.log(User); 
console.log(Profile); 

JS Fiddle

+0

當前的代碼添加一個新的領域的原因是你傳遞的「參數」的方式。你需要一個字符串(不是數組),而且你不能按照你的方式組合兩個索引。例如'update(User [「local」],「location」,...'和'update(Profile,「location」,...'。你的函數也應該讀取'model [parameter]',而不是'model [updatedLocation]'。 –

回答

1

你可以給這個一試。基本上,這是一種通用的方式去到對象中的任何級別並更新屬性。在代碼中詳細評論

var User = { 
 
    local: { 
 
    location: { 
 
     city: "", 
 
     state: "" 
 
    } 
 
    } 
 
} 
 

 
var Profile = { 
 
    location: { 
 
    city: "", 
 
    state: "" 
 
    } 
 
} 
 

 
function update(obj, path, updatedProps) { 
 
    var objToUpdate = obj; 
 
    // Iterate down the path to find the required object 
 
    for (var i = 0; i < path.length; i++) { 
 
    if (objToUpdate[path[i]]) { 
 
     objToUpdate = objToUpdate[path[i]] 
 
    } else { 
 
     // If any path is not found, then no point continuing 
 
     objToUpdate = null; 
 
     break; 
 
    } 
 
    } 
 
    if (objToUpdate) { 
 
    var props = Object.keys(updatedProps); 
 
    for (var j = 0; j < props.length; j++) { 
 
     var prop = props[j]; 
 
     objToUpdate[prop] = updatedProps[prop] || objToUpdate[prop]; 
 
    } 
 
    } 
 
    return obj; 
 
} 
 

 
update(User, ["local", "location"], { 
 
    city: "ny", 
 
    state: "ny" 
 
}); 
 
update(Profile, ["location"], { 
 
    city: "ny", 
 
    state: "ny" 
 
}); 
 

 
console.log("User:", User); 
 
console.log("Profile:", Profile);

+0

謝謝這個作品! – Shivam

0

這裏的其他答案相似,但它不需要location結構的明確編碼:

function update(model, parameter, newVal) { 
    model[parameter] = newVal; 
} 

update(User["local"], "location", { city: "ny", state: "ny"}); 
update(Profile, "location", { city: "ny", state: "ny"}); 

或者,如果你只更新位置,你可以簡化功能:

function updateLocation(model, newVal) { 
    model.location = newVal; 
} 
相關問題