0

var resources = ["user$manageuser", "user$createuser", "details$/user-details-data", "page1$user$deletesupplier"]

var result = resources.reduce(
  (r, s) =>
  ((key, value) => Object.assign(r, {
    [key]: [].concat(r[key] || [], value)
  }))
  (...s.split('$')), {}
);
console.log(result);

not able to nest the level for page1, how can i do that one ?

expectedoutput = {
 user: ["manageuser", "createuser"],
 details: ["/user-details-data"],
 page1: {
    user: ["deletesupplier"]
  }
}
2
  • what is the max depth of the object? e.g depth of page1$user$deletesupplier is 3 Commented Mar 11, 2019 at 8:28
  • no it can be any level ?thats the problem if its a fixed level it was fine but it can be any level Commented Mar 11, 2019 at 8:37

2 Answers 2

4

you have to use recursion

const data = ["user$manageuser", "user$createuser", "details$/user-details-data", "page1$user$deletesupplier"]

function makeObject(resources, object = {}) {
  return resources.reduce((result, string) => {
    const [key, value] = string.split(/\$(.+)/)
    if (value && value.includes('$')) {
      result[key] = result[key] || {}
      makeObject([value], result[key])
    } else {
      result[key] = result[key] || []
      result[key].push(value)
    }
    return result
  }, object)
}

const res = makeObject(data)
console.log(res)

This works for any depth, and also you can add objects to array, ex. "user$test$test2"

Sign up to request clarification or add additional context in comments.

3 Comments

i was trying with recursion, cool thanks for the quick response :)
instead of $ if i use pipeline i am not able to split as like $, is the regex should change ?
got it split(/\|(.+)/) :)
1

If You can use Lodash or at least get and set from this library then function what will solve your problem can look like this:

function transform(resources) {
    return resources.reduce((agg, resource) => {
      const splitted = resource.split('$');
      const keys = splitted.slice(0, splitted.length - 1);
      const value = splitted[splitted.length - 1];

      _.set(agg, keys, [...(_.get(agg, keys) || []), value]);


      return agg;
    }, {});
  }

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.