Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - map array with dots between names to nested fields

I'm trying to convert array of strings with dots between names. I want to make an array of object like in const out. I tried to make it by reduceRight, but I don't know how to combine fields.

My code:

const input = ['apples', 'bananas.kivi.grape', 'bananas.orange', 'bananas.strawberry'];
const res = input.map((item) => {
  const splInp = item.split('.');
  return splInp.reduceRight((acc, item) => {
    if (Object.keys(acc).length !== 0) {
      return {
        children: [acc],
        "name": item
      };
    } else {
      return {
        "name": item
      };
    }
  }, []/* as any*/);
});
console.log(res);
question from:https://stackoverflow.com/questions/65904384/map-array-with-dots-between-names-to-nested-fields

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

1 Reply

0 votes
by (71.8m points)

You can solve it using a trie

Whenever you get a string, just traverse your tree and eventually add any leaf (if you can't traverse more)

const input = ['apples', 'bananas.kivi.grape', 'bananas.orange', 'bananas.strawberry', 'apples.are.good', 'apples.are.not.good'];
const Trie = () => {
  const root = {}
  const add = s => {
    s.split('.').reduce((acc, tok) => {
      if (!acc[tok]) {
        // add the leaf
        acc[tok] = { children: {} }
      }
      // traverse the node
      return acc[tok].children
    }, root)
  }
  const toJSON = (node = root) => {
    return Object.entries(node).map(([name, { children }]) => ({
      name, children: toJSON(children)
    }))
  }
  return { add, toJSON }
}
const t = Trie()
input.forEach(t.add)
console.log(JSON.stringify(t.toJSON(), null, 2))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...