試試這個:
function setObj(originalObj, path, value){
var parts = path.split(',');
var lastKey = parts.pop();
var obj = originalObj;
parts.forEach(
function(key) {
key = key.trim();
obj[key] = obj[key] || {};
obj = obj[key];
}
);
obj[lastKey] = value;
}
var originalObj = {};
var test = "This is a test";
setObj(originalObj, 'property,company,city', test)
console.log(JSON.stringify(originalObj,0,2));
它遍歷列表併爲除最後一個以外的所有列創建子對象。然後它使用最後的密鑰來存儲value
。
此代碼的優點是您不會假定原始對象變量名稱。而且,如果你想要它是純粹的,而不是影響原始的對象結構,那麼你可以做出這些小的改變:
function setObj(originalObj, path, value){
var parts = path.split(',');
var lastKey = parts.pop();
var newObj = Object.assign({}, originalObj);
var obj = newObj;
parts.forEach(
function(key) {
obj[key] = Object.assign({}, obj[key] || {});
obj = obj[key];
}
);
obj[lastKey] = value;
return newObj;
}
var originalObj = {animals: {dog:"bark",cat:"meow"},property:{company:{name:"Fred's Things"}}};
var test = "This is a test";
var result = setObj(originalObj, 'property,company,city', test)
console.log(JSON.stringify(originalObj,0,2));
console.log(JSON.stringify(result,0,2));
哦,有趣。這並不難,但它在JavaScript 101課程中提供了一個很好的家庭作業練習。 – melpomene
你有什麼嘗試過......有什麼問題? – vol7ron