将字符串数组映射为特定对象数组



我有一个问题,使字符串数组的url路径对象(为面包屑)

我有这样一个数组:

const array = ['visit', 'schedule', 'validator']

What I tried:

const routeArray = array.map((b) => ({
label: b,
route: `/${b}`,
}))
console.log(routeArray)

结果:

[  
{label: "visit", route: "/visit"},
{label: "schedule", route: "/schedule"},
{label: "validator", route: "/validator"},
] 

我想要达到的目标:

[
{label: "visit", route: "/visit"},
{label: "schedule", route: "/visit/schedule"},
{label: "validator", route: "/visit/schedule/validator"}
]

有什么帮助吗?

在遍历数组时连接字符串:

const array = ['visit', 'schedule', 'validator'];
let route = "";
const result = array.map(label => {
route += '/' + label;
return { label, route };
});

Array.prototype.map(),Array.prototype.slice()Array.prototype.join()可以是你最好的朋友,在这里:

const input = ['visit', 'schedule', 'validator'];
const output = input.map((item, index) => {
return {
label: item,
route: '/' + input.slice(0, index + 1).join('/')
}
});
// test
console.log(output);

请查看并告诉我这是否是您正在寻找的:

const array = ['visit', 'schedule', 'validator'] 
const newArray = array.map((entry, index) => {
const route = [];

for (let i = 0; i < index + 1; i++) {
route.push(array[i]);
}

return {
label: entry,
route: route.join('/'),
};
});
console.log(newArray);

在这种方法中,我循环通过as many元素as the ordercurrent elementarray,pushing它们到route array。当创建对象属性时,我用'/'分隔joinelements of route

下面是我们如何使用reduce方法来做到这一点:

const arr = ["visit", "schedule", "validator"];
const res = arr.reduce((acc, curr, idx, self) => {
// Our route property of our needed data structure
const route = `/${self.slice(0, idx)}${idx > 0 ? "/" + curr : curr}`;
// Our new object
const obj = { label: curr, route };
return [...acc, obj];
}, []);
console.log(res);

可以使用for循环来完成。您需要有一个变量来跟踪您的incrementing路由,并在循环迭代中持续存在。

const array = ['visit', 'schedule', 'validator'];
let ansArray = [];
let incrVal = '';
for(let i = 0 ; i < array.length; i++){
let ans = incrVal + '/' + array[i];
ansArray.push({'label' : array[i], 'route' : ans});
incrVal = ans;
}
console.log(ansArray);

const array = ['visit', 'schedule', 'validator'];
const results = array.map((item, index, arr) => {

return {
label: item,
route: '/' + arr.slice(0, index + 1).join('/'),
};
});
console.log(results);

使用减少数组方法

const array = ["visit", "schedule", "validator"];
const res = array.reduce((acc, curr, idx, arr) => {
acc.push({
label: curr,
route:'/'+ arr.slice(0, idx + 1).join('/')
})
return acc;
}, []);
console.log(res);

我认为这是最短的方法:

const input = ["visit", "schedule", "validator"];
const res = input.map((label, i, arr) => ({
label,
route: '/' + arr.slice(0, i + 1).join("/")
}));
console.log(input);
console.log(res);