Try to search your question here, if you can't find : Ask Any Question Now ?

Making the desired data into an object having nested objects with key and values

HomeCategory: stackoverflowMaking the desired data into an object having nested objects with key and values
Avatarpushpa asked 4 months ago

I have a below structure of data. I need to get desired output as shown below.

I tried using a recursive function since the expected structure is as follows is recursive, but how can I make this as a key value?

Is there any better way to achieve this?

input data

let data = {
      users: [
        {
          terms: ["service|/users"],
          conditions: ["view", 'create']
        },
        {
          terms: ["service|/users-details"],
          conditions: ["view"]
        },
        {
          terms: ["service|/usersNew"],
          conditions: ["view"]
        },
        {
          terms: ["list|searchuser"],
          conditions: ["view"]
        },
        {
          terms: ["list|createuser"],
          conditions: ["view", "create"]
        },
        {
          terms: ["service|/user-contacts"],
          conditions: ["view"]
        },
        {
          terms: ["service|/user-location"],
          conditions: ["view"]
        },
        {
          terms: ["searchuserslist|button|select-button"],
          conditions: ["enable"]
        }
      ]
    };

expected output

{
  list: [{ searchuser: ["view"] }, { createuser: ["view", "create"] }],
  service: [{/users: ['view', 'create']}, {/users-details: ['view']}, {/usersNew: ['view']}, {/user-contacts: ['view']}, {/user-location: ['view']}]
  searchuserslist: {
    button: [{select-button: ['enable']}]
  }
}

snippet that I tried

   function resolvingData(data, object = {}) {
      return data.reduce((result, string) => {
        const [key, value] = string.split(/|(.+)/);
        if (value && value.includes("|")) {
          result[key] = result[key] || {};
          resolvingData([value], result[key]);
        } else {
          result[key] = result[key] || [];
          result[key].push(value);
        }
        return result;
      }, object);
  }
1 Answers
Best Answer
Avatarnaveen answered 4 months ago
Your Answer

20 + 9 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com