简体   繁体   中英

How can i convert an object in a specific format into another format

I am having a hard time trying to convert an object supplied in a specific format from API into a target format using javascript. Please note that in the target format, the false values are not present. This is intentional. Can someone please help by showing how I can do the this kind of conversion. Thank you

// Original format

    const rules= [
      {
        dealer: {
          view: true,
          edit: false,
          add: false
        },
        franchise: {
          view: true,
          edit: true,
          add: true
        },
         branch: {
          view: true,
          edit: false,
          add: false
        }
      }
    ]


// Target format

  const rules = [
          {
            actions: ["view"],
            subject: ["dealer"]
          },
          { 
            actions: ["view"],
            subject: ["franchise"]
          },
          { 
            actions: ["edit"],
            subject: ["franchise"]
          },
          { 
            actions: ["add"],
            subject: ["franchise"]
          },
          { 
            actions: ["view"],
            subject: ["branch"]
          }
        ];

I implemented mapping function which take each item and map it according to the value if true

    let rules = [
        {
            dealer: {
                view: true,
                edit: false,
                add: false
            },
            franchise: {
                view: true,
                edit: true,
                add: true
            },
            branch: {
                view: true,
                edit: false,
                add: false
            }
        }
    ]

    rules = rules.map(item => {
        const keys = Object.keys(item);
        let mappedItem = []
        keys.forEach(key => {
            for (const property in item[key]) {
                if (item[key][property]) {
                    mappedItem.push({ subject: [key], actions: [property] })
                }
            }
        })
        return mappedItem;
    });

 let rules= [ { dealer: { view: true, edit: false, add: false }, franchise: { view: true, edit: true, add: true }, branch: { view: true, edit: false, add: false } } ]; const result = rules.map(obj => Object.keys(obj).map(k => ({ subject: [k], actions: Object.keys(obj[k]).filter(action => obj[k][action]) })).reduce((acc, cur) => ([ ...acc, ...cur.actions.map(a => ({subject: cur.subject, actions: [a]})) ]),[])) console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM