假设我有一个像'user.data'
这样的字符串,并且我想创建该对象的data
字段:
const obj = {
user: {
data: {}
}
}
我无法使用此字符串正常执行(obj['user.data'] = {}
),因为它将执行以下操作:
const obj = {
user: {},
'user.data': {}
}
那不是我想要的。
当对象是字符串的最后一部分时,如何使用对象创建属性?
const str = 'user.hobbies';
const obj = { user: {} };
addInNestedProp(str, obj);
console.log(obj);
// => { user: { hobbies: {} } }
答案 0 :(得分:0)
这里是一种解决方案,允许您采用诸如“ user.hobbies”之类的字符串,根据该字符串评估对象,并向该对象添加该字符串中而不是该对象中的任何属性。 / p>
使用输入字符串“ user.hobbies”将产生:
{
"name": "me",
"user": {
"avatarURL": "longURL",
"hobbies": {}
}
}
您也可以使用“ user.hobbies.sports.basketball”进行尝试,它将产生您期望的对象层次结构。
该代码已被大量记录:
const existing = { name: 'me', user: { avatarURL: 'longURL' }};
const addInHobbyString = 'user.hobbies';
const newObject = addInObject(addInHobbyString, existing);
console.log(newObject);
function addInObject(term, obj) {
// make a clone of the object
let objCopy = JSON.parse(JSON.stringify(obj));
// separate serach terms
let terms = term.split('.');
// set temp obj to first search term as object property
// any modifications to temp will be seen in objCopy
let temp = objCopy[`${terms[0]}`];
// Find the last search term that exists as an object property
let q = terms.reduce((acc, curr, idx) => (objCopy[`${curr}`]) ? null : idx, 0);
// Do the work
for (let i = 1; i <= q; i++) {
// if property doesn't exist on object create it and set it to an empty object
if (!temp[`${terms[i]}`]) {
temp[`${terms[i]}`] = {};
// Set the search depth in our temp object to the next depth
temp = temp[`${terms[i]}`]
}
}
return objCopy;
}