【问题标题】:Add object name to field inside object将对象名称添加到对象内的字段
【发布时间】:2021-06-24 11:53:22
【问题描述】:

假设我有一个看起来像这样的对象

const randomObj = {
  myObj: { id: "1", value: "random string", text: "random text"},
  otherObj: { id: "2", value: "random string 2", text: "random text 2"}
}

我想遍历每个对象及其值,但向对象添加一个附加字段

const newObj = { ..._.mapValues(randomObj) }

预期输出

newObj: {
          myObj: { id: "1", value: "random string", text: "random text"},
          otherObj: { id: "2", value: "random string 2", text: "random text 2"},
        }

想要的输出

 newObj: {
         myObj: { id: "1", value: "random string", text: "random text", objectId: "myObj"},
         otherObj: { id: "2", value: "random string 2", text: "random text 2", objectId: "otherObj"},
         } 

如何添加该附加字段,其中附加字段将是对象的名称?

【问题讨论】:

    标签: javascript oop functional-programming lodash


    【解决方案1】:

    _.mapValues() iteratee 被调用,属性的值作为第一个参数,键作为第二个参数,整个对象作为第三个参数。使用对象扩展创建一个新对象,其键为objectId

    const randomObj = {
      myObj: { id: "1", value: "random string", text: "random text"},
      otherObj: { id: "2", value: "random string 2", text: "random text 2"}
    }
    
    const newObj = _.mapValues(randomObj, (v, k) => ({
      ...v,
      objectId: k
    }))
    
    console.log(newObj)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>

    如果没有 lodash,您可以使用 Object.entries() 将对象转换为 [key, value] 对的数组,映射对,然后使用 Object.fromEntries() 将对数组转换回对象。

    const randomObj = {
      myObj: { id: "1", value: "random string", text: "random text"},
      otherObj: { id: "2", value: "random string 2", text: "random text 2"}
    }
    
    const newObj = Object.fromEntries(
      Object.entries(randomObj)
        .map(([k ,v])  => [k, {
          ...v,
          objectId: k
        }])
    )
    
    console.log(newObj)

    【讨论】:

      【解决方案2】:

      const randomObj = {
        myObj: { id: "1", value: "random string", text: "random text"},
        otherObj: { id: "2", value: "random string 2", text: "random text 2"}
      }
      
      
      Object.keys(randomObj).forEach(key => randomObj[key].objectId = key);
      
      console.log(randomObj);

      【讨论】:

        【解决方案3】:

        使用原生方法 Object.entries() 和 Array#reduce() 就像使用 lodash 一样简单

        const randomObj = {
          myObj: { id: "1", value: "random string", text: "random text"},
          otherObj: { id: "2", value: "random string 2", text: "random text 2"}
        },
        
        res = Object.entries(randomObj).reduce((a,[k,v])=>(a[k] = {...v, objectId:k},a),{})
        
        console.log(res)

        【讨论】:

          猜你喜欢
          • 2020-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-02
          • 1970-01-01
          相关资源
          最近更新 更多