Search code examples
javascriptobjectarrow-functions

Function stored in object property returns array instead of object


I'm trying to set an object property using a function that returns and object.

The problem is when setting the property I'm getting back an array as a value instead of the object.

const newUserRights = {
  A: { id: '1'},
  B: { id: '2'},
  C: { id: '3'},
  D: { id: '4'},
  E: { id: '5'},
  F: { id: '6'},
  G: { id: '7'},
};

var Post = {
  name: '',
  rs: function r(rights = []) {
    let r = {};
    for (let [k, v] of Object.entries(newUserRights)) {
      r[v.id] = false;
    }
    if (rights.length > 0) {
      for (ri of rights) {
        r[ri] = true;
      }
    }
    return r;
  },
};

// trying to set the property
Post.rs = ['1', '2'];

Desired output:

Post: {
    name:'',
    rs:{
        1: true,
        2: true,
        3: false,
        4: false,
        5: false,
        6: false,
        7: false
    }
}

But getting:

Post: {
    name:'',
    rs:['1', '2']
}

I want to know

  • what I'm doing wrong
  • How to return the Object
  • Is this a good practice

Thank you


Solution

  • There are lots of ways to do this, but this keeps the solution close to your attempt.

    I considered an implementation using this, but thought that would add unhelpful complexity.

    I will note, however, that any time you have a series of incrementing integers, an Array should be considered because it has those keys implicitly.

    const newUserRights = {
      A: { id: '1'},
      B: { id: '2'},
      C: { id: '3'},
      D: { id: '4'},
      E: { id: '5'},
      F: { id: '6'},
      G: { id: '7'},
    };
    
    const applyRights = (o, rights = []) => {
      const rs = {};
      for (const [, { id }] of Object.entries(newUserRights)) {
        rs[id] = false;
      }
      
      for (const r of rights) {
        rs[r] = true;
      }
      
      o.rs = rs;
      return o;
    };
    
    const Post = { name: '' };
    console.log(applyRights(Post, ['1', '2']));