Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a hash like the one below

aa: {
  categories: {
   cat1: 'alpha'
  }
}

Starting from the string 'aa.categories.cat1', how can I get alpha suing plain JS?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

Using split() and reduce():

const result = path.split('.').reduce((a, v) => a[v], object);

Complete snippet:

const object = {
  aa: {
    categories: {
      cat1: 'alpha'
    }
  }
}

const path = 'aa.categories.cat1';

const result = path.split('.').reduce((a, v) => a[v], object);

console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...