0

I have a problem to make an array of strings into objects of url paths (for breadcrumbs)

I have this array :

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

What I tried :

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

result :

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

what I want to achieve :

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

Any help ?

2
  • 1
    Could you share what you have tried so far, please? Please notice that people are expected to make some effort to solve the problem by their own before asking here. Commented Jul 30, 2021 at 9:34
  • @secan Sure! I edited the post Commented Jul 30, 2021 at 10:28

8 Answers 8

2

Just concatenate the String while going through the array:

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

let route = "";

const result = array.map(label => {
    route += '/' + label;
    return { label, route };
});
Sign up to request clarification or add additional context in comments.

Comments

1

Array.prototype.map(), Array.prototype.slice() and Array.prototype.join() can be your best friends, here:

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);

1 Comment

Simple and effective! Thanks for answering
1

Please check this out and let me know if this is what you were looking for:

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);

In this approach, I loop through as many elements as the order of the current element of array, pushing them into the route array. When creating the object properties, I join the elements of route separated by '/'.

Comments

0

Here is how we can do this using the reduce method:

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);

1 Comment

The expected output matches one-to-one with the input; using Array.prototype.reduce() for this case would add unnecessary complexity, in my opinion.
0

Can be done using a for loop. You need to have a variable which tracks your incrementing route and persists over loop iterations.

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);

Comments

0

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);

Comments

0

Using reduce array method

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);

Comments

0

I think this is the shortest way to do this:

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.