2 回答

TA貢獻1851條經驗 獲得超3個贊
沒有內置功能。
但是有很多第三方模塊可用于此任務。
例如,您可以使用lodash's _.set。文檔在這里,您也可以單獨使用它而無需添加完整lodash的包,而是使用lodash.set包。
例如,來自文檔:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4
_.set(object, ['x', '0', 'y', 'z'], 5);
console.log(object.x[0].y.z);
// => 5
如果你不喜歡,_.set還有很多 其他的 選擇 。

TA貢獻1793條經驗 獲得超6個贊
你可以這樣做:
var string = "position.x : 1";
var split = string.split(/\.|\:/); // split the strig into an array by '.' and ':'
var obj = {}; // result object
function getObject(split) {
obj[split[0].trim()] = {};
obj[split[0].trim()][split[1].trim()] = split[2].trim();
}
getObject(split); // call the function and pass the array of values
console.log( obj ); // print the whole result object
console.log( obj['position']['x'] ); // print obj['position']['x']
添加回答
舉報