【问题标题】:Assigning the key of the object as a value inside that object将对象的键分配为该对象内的值
【发布时间】:2018-01-10 20:32:01
【问题描述】:

在 lodash 中,我们有我正在使用的 _mapKeys 方法,如下所示:

这是一个对象数组:

const posts = [
  {
    id: 123,
    title: 'Hello',
  },
  {
    id: 321,
    title: 'World',
  },
];

从那里我使用这样的方法:

const postsObjWithKeys = _.mapKeys(posts, 'id');

console.log(postsObjWithKeys);

结果是:

{
  123: {id: 123, title: 'Hello'},
  321: {id: 321, title: 'World'}
}

完美!正是我想要的!

问题是我如何在“反向”中实现这一目标?意思是如果我有这样的对象:

const posts = {
  123: {
    title: 'Hello' 
  },
  321: {
    title: 'World'
  }
}

如果是 id,是否可以获取密钥并将其分配为值?最终结果是:

const posts = {
  123: {
    id: 123,
    title: 'Hello' 
  },
  321: {
    id: 321,
    title: 'World'
  }
}

【问题讨论】:

    标签: javascript arrays object lodash


    【解决方案1】:

    使用 lodash,您可以使用 _.mapValues() 实现相反的效果:

    const posts = {
      123: {
        title: 'Hello' 
      },
      321: {
        title: 'World'
      }
    }
    
    const result = _.mapValues(posts, (value, id) => _.assign({}, value, { id }));
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    【讨论】:

    • 我怎么没有想到呢?我需要睡眠。谢谢!
    【解决方案2】:

    只需迭代所有键并将它们添加为对象上的id

    const posts = {
      123: {
        title: 'Hello' 
      },
      321: {
        title: 'World'
      }
    }
    
    Object.keys(posts).forEach(k=>{
        posts[k].id = k;
    });
    
    console.log(posts);
    
    /*
    const posts = {
      123: {
        id: 123,
        title: 'Hello' 
      },
      321: {
        id: 321,
        title: 'World'
      }
    }
    */

    【讨论】:

    • 比库方法简单
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2017-12-08
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    相关资源
    最近更新 更多