将多个对象索引转换为嵌套数组可以通过以下步骤实现:
以下是一个示例代码,演示如何将多个对象索引转换为嵌套数组:
function convertToNestedArray(indexes) {
let nestedArray = [];
for (let index of indexes) {
let keys = index.split('.');
let currentLevel = nestedArray;
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
let existingLevel = currentLevel.find(item => item.key === key);
if (!existingLevel) {
existingLevel = { key: key, value: {} };
currentLevel.push(existingLevel);
}
if (i === keys.length - 1) {
existingLevel.value = index;
}
currentLevel = existingLevel.value;
}
}
return nestedArray;
}
// 示例用法
let indexes = ['a.b.c', 'a.b.d', 'a.e', 'f'];
let result = convertToNestedArray(indexes);
console.log(result);
上述代码将多个对象索引 ['a.b.c', 'a.b.d', 'a.e', 'f']
转换为以下嵌套数组:
[
{
key: 'a',
value: {
key: 'b',
value: {
key: 'c',
value: 'a.b.c'
},
{
key: 'd',
value: 'a.b.d'
}
}
},
{
key: 'a',
value: {
key: 'e',
value: 'a.e'
}
},
{
key: 'f',
value: 'f'
}
]
这样,每个对象索引都被正确地转换为了嵌套数组的形式。
领取专属 10元无门槛券
手把手带您无忧上云