0

What I have is:

routeLinks = {
    Store: '/store',
    Department: '/department',
    Home: '/home'
}

What I want is:

routeLinks = {
    Store: 'store',
    Department: 'department',
    Home: 'home'
}

i.e. modified object values with first character removed

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Ashish Kumar
  • 401
  • 4
  • 11

3 Answers3

4

Use slice:

const routeLinks = { Store: '/store', Department: '/department', Home: '/home' };

const res = Object.entries(routeLinks).reduce((a, [k, v]) => (a[k] = v.slice(1), a), {});

console.log(res);

Or just use for...in:

const routeLinks = { Store: '/store', Department: '/department', Home: '/home' };

for (let k in routeLinks) {
  routeLinks[k] = routeLinks[k].slice(1);
}

console.log(routeLinks);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
2

You can loop through the object with for...in loop and substring the value:

var routeLinks = {
  Store: '/store',
  Department: '/department',
  Home: '/home'
}
for(var k in routeLinks){
  routeLinks[k] = routeLinks[k].substring(1);
}
console.log(routeLinks);

Update: Solution using forEach() and arrow function (=>)

var routeLinks = {
  Store: '/store',
  Department: '/department',
  Home: '/home'
};
Object.keys(routeLinks).forEach(k => routeLinks[k] = routeLinks[k].substring(1));
console.log(routeLinks);
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

Here is a functional version that doesn't mutate the input

routeLinks = {
    Store: '/store',
    Department: '/department',
    Home: '/home'
};

const trimStart = obj => Object.keys(obj).reduce((result, key) => ({...result, [key]: obj[key].substr(1) }), {});

console.log(trimStart(routeLinks));
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60