我有这个物体:
{
'categories[0].alias': 'gyms',
'categories[0].title': 'Gyms',
'categories[1].alias': 'healthtrainers',
'categories[1].title': 'Trainers',
'location.display_address[0]': '360 Hampton Dr',
'location.display_address[1]': 'Venice, CA 90291'
}
...我正在尝试将其转变为这样:
{
categories: [
{ alias: 'gyms', title: 'Gyms' },
{ alias: 'healthtrainers', title: 'Trainers' }
],
location: {
display_address: [ '360 Hampton Dr', 'Venice, CA 90291' ]
}
}
我尝试了这些答案。每个输出都略有不同 - 第二个更接近 - 但都无法正确处理带有方括号数字/数组位置的键。
处理这个问题的最佳方法是什么?
我认为我们可以使用这个答案中的方法,这是您提供的示例的示例代码:
const deepSet = (obj, path, val) => {
path = path.replaceAll("[", ".[");
const keys = path.split(".");
for (let i = 0; i < keys.length; i++) {
let currentKey = keys[i];
let nextKey = keys[i + 1];
if (currentKey.includes("[")) {
currentKey = parseInt(currentKey.substring(1, currentKey.length - 1));
}
if (nextKey && nextKey.includes("[")) {
nextKey = parseInt(nextKey.substring(1, nextKey.length - 1));
}
if (typeof nextKey !== "undefined") {
obj[currentKey] = obj[currentKey] ? obj[currentKey] : (isNaN(nextKey) ? {} : []);
} else {
obj[currentKey] = val;
}
obj = obj[currentKey];
}
};
const result = {};
const originalObj = {
'categories[0].alias': 'gyms',
'categories[0].title': 'Gyms',
'categories[1].alias': 'healthtrainers',
'categories[1].title': 'Trainers',
'location.display_address[0]': '360 Hampton Dr',
'location.display_address[1]': 'Venice, CA 90291'
};
for (const [key, value] of Object.entries(originalObj)) {
deepSet(result, key, value);
}
console.log(result);