从数据数组创建嵌套对象和数组

时间:2019-03-11 08:16:22

标签: javascript

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

无法嵌套page1的级别,我该怎么做?

expectedoutput = {
 user: ["manageuser", "createuser"],
 details: ["/user-details-data"],
 page1: {
    user: ["deletesupplier"]
  }
}

2 个答案:

答案 0 :(得分:4)

您必须使用递归

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)

这适用于任何深度,也可以将对象添加到数组,例如。 "user$test$test2"

答案 1 :(得分:1)

如果您可以使用Lodash或至少从该库中获取和设置,则可以解决问题的函数如下所示:

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;
    }, {});
  }