【问题标题】:Restructuring an object with map and forEach用 map 和 forEach 重构对象
【发布时间】:2017-08-12 23:01:04
【问题描述】:

我有一个对象,我正试图映射到一个反应组件(使用 lodash)。我从 API(firebase)返回的对象的当前形状如下所示......

// ex. 1
{
  "-Kdkahgiencls0dnh": {
    "name": "a name",
    "desc": "a description",
    "other": "some other guff"
  },
  "-Ksdfadfvcls0dsnh": {
    "name": "another name",
    "desc": "another description",
    "other": "some more"
  },
  "-kgoandiencls0dnh": {
    "name": "I am a name",
    "desc": "I am a description",
    "other": "I am some other guff"
  }
}

...但是,当我运行_.map()时,我失去了主键

我想要做的是让我的对象变成以下形状:

// ex. 2
[
  {
    "id": "-Kdkahgiencls0dnh",
    "name": "a name",
    "desc": "a description",
    "other": "some other guff"
  },
  {... the next object ...},
  {... etc ...}
]

我现在正在做的是在 componentWillMount 生命周期方法中获取我的数据,如下所示:

componentWillMount() {
  firebaseRef.on('value', snap => {
    let data = snap.val() // the whole original object (see ex. 1)
    let tempArray = [] // an array to store my newly formatted objects
    _.forEach(data, (item, key) => {
      // Here's where i'm not really sure what to do.
      // I want to use Object.assign to set a new key:value
      // That adds "id": "-theobjectsmainkey" to a new object
      // then push to my tempArray and finally setState with the
      // correctly formatted array of objects.
    })
  })
}

想法?想法?谢谢。

【问题讨论】:

    标签: javascript arrays reactjs object lodash


    【解决方案1】:

    您可以使用Object.entries().map() 和对象传播

    const data = {
      "-Kdkahgiencls0dnh": {
        "name": "a name",
        "desc": "a description",
        "other": "some other guff"
      },
      "-Ksdfadfvcls0dsnh": {
        "name": "another name",
        "desc": "another description",
        "other": "some more"
      },
      "-kgoandiencls0dnh": {
        "name": "I am a name",
        "desc": "I am a description",
        "other": "I am some other guff"
      }
    }
    
    let res = Object.entries(data).map(([id, prop]) => ({id, ...prop}));
    
    console.log(res);

    【讨论】:

    • 是的!这正是我所追求的。我希望我能更好地掌握这是在做什么......
    • 这很有帮助。谢谢!
    • 请记住,您将需要一个用于 Object.entries 的 polyfill。更传统的方法是使用 Object.keys 迭代对象
    • @aaaaaa Polyfills 在需要时可用,并在上面的评论中链接。
    【解决方案2】:

    Lodash 的 _.map() 回调接收作为第二个参数的迭代键。使用object assign,创建一个key为id的新对象:

    const array = _.map(data, (item, id) => Object.assign({ id }, item))
    

    演示:

    const data = {"-Kdkahgiencls0dnh":{"name":"a name","desc":"a description","other":"some other guff"},"-Ksdfadfvcls0dsnh":{"name":"another name","desc":"another description","other":"some more"},"-kgoandiencls0dnh":{"name":"I am a name","desc":"I am a description","other":"I am some other guff"}};
    
    const array = _.map(data, (item, id) => Object.assign({ id }, item));
    
    console.log(array);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    【讨论】:

    • 就我个人而言,我不喜欢 lodash 的 map 风格如何接受一个集合并输出一个数组,但这种行为正是 OP 正在寻找的。​​span>
    【解决方案3】:

    给你,只使用纯 JS:

    const raw = {
      "-Kdkahgiencls0dnh": {
        "name": "a name",
        "desc": "a description",
        "other": "some other guff"
      },
      "-Ksdfadfvcls0dsnh": {
        "name": "another name",
        "desc": "another description",
        "other": "some more"
      },
      "-kgoandiencls0dnh": {
        "name": "I am a name",
        "desc": "I am a description",
        "other": "I am some other guff"
      }
    }
    
    let formatted = Object.keys(raw).map(
      key=>Object.assign(raw[key], {"id": ""+key})
    );
    

    这里是fiddle 以获得现场演示。

    【讨论】:

      【解决方案4】:
      componentWillMount() {
        firebaseRef.on('value', snap => {
          let data = snap.val() // the whole original object (see ex. 1)
          let tempArray = Object.keys(data).map((item, key) => {
              return {
                  "id": item,
                  "name": data[item].name // etc, a structure what you want
                  ...
              };
          })
        })
      }
      

      【讨论】:

      • 第一个例子给出:[ { "desc": "First description", "subtitle": "First subtitle", "title": "First Project Title" }, { "desc": "No need for a description here. Nothing to see", "subtitle": "Subtitle of the gods", "title": "Another Project" }, { "desc": "If i had a desc it would go here", "subtitle": "I am subtitle hear me roar", "title": "Final project example" } ]
      • 这里不添加id属性
      猜你喜欢
      • 1970-01-01
      • 2016-04-15
      • 2021-09-30
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      相关资源
      最近更新 更多