【问题标题】:What is the best way to copy only certain values from every object in array into another array?将数组中每个对象的某些值仅复制到另一个数组中的最佳方法是什么?
【发布时间】:2020-03-03 07:50:25
【问题描述】:

由于 Bootstrap Vue Form Select 元素使用数组中对象的“文本”和“值”值,我想从现有数组创建一个新数组,其中每个对象都包含多个值。我需要从现有数组中的每个对象中复制其中两个值(“id”和“msg”),并在新数组中创建具有相同索引的对象,使用“id”和“msg”中的值来填充他们的“文本”和“价值”值。最好的方法是什么?

这是我想出的:

selectoptions(){
  var options = [];
  for (var i in this.proposals) {
    options[i] = { value: this.proposals[i].id, text: this.proposals[i].msg};
  }
  return options;
}

我想知道是否有更好的方法来做到这一点,可能使用 Array.prototype.map。

【问题讨论】:

  • 使用Array.prototype.map。此外,向我们展示一些示例数据以及您实际尝试过的内容总是很有帮助的。
  • 更新了我的帖子。你能解释一下我如何使用 Array.prototype.map 吗?

标签: javascript arrays vue.js


【解决方案1】:

如果提案是一个对象,那么这样做:

const result = Object.keys(this.proposals).map((key) => ({
    value: this.proposals[key].id,
    text: this.proposals[key].proposal
}))

如果提案是一个数组

   const result = this.proposals.map((currentProposal) => ({
        value: currentProposal.id,
        text: currentProposal.proposal
    }))

【讨论】:

    【解决方案2】:

    这将完成工作:

    this.proposals = this.proposals.map(el => {
        return {value:el.id, text: el.msg}
    });
    

    你可以see hereArray.map函数的文档。

    【讨论】:

      【解决方案3】:

      您可以创建一个 pick 函数来仅从对象中选择所需的属性,将所需的映射从现有对象传递到新对象。我们可以使用 Object.entries,然后 filter 和 Object.fromEntries 来做到这一点。

      例如:

          let a = [{ 
              id: 1,
              msg: 'Some msg 1',
              data: 'Some data'
          },
          { 
              id: 2,
              msg: 'Some msg 2',
              data: 'Some data'
          },
          { 
              id: 3,
              msg: 'Some msg 3',
              data: 'Some data'
          },
      ]
      
      function pick(obj, propertyMapping) {
          return Object.fromEntries(Object.entries(obj).reduce((acc, [key, value]) => {
            if (propertyMapping[key]) { 
              acc.push([propertyMapping[key], value]);
            }
            return acc
        } , []));
      }
      
      console.log(a.map((el) => pick(el, { id: "value", msg: "text" } )));

      【讨论】:

        【解决方案4】:

        除了映射到新数组之外,您还可以使用现有数组。 b-select 允许您在其标签内写入b-select-option,这些标签将用作选项。 因此,您可以使用现有数组创建一个v-for,并将id 添加为值,将msg 添加为b-select-option 中的文本。

        如果在选择值时需要整个对象,也可以将其传递给 value 属性,选择的 v-model 将返回整个对象。

        new Vue({
          el: '#app',
          data() {
            return {
              selected: null,
              selected2: null,
              messages: [
                { id: 1, msg: 'This is message 1', user: 'Hiws' },
                { id: 2, msg: 'This is message 2', user: 'Hiws' },
                { id: 3, msg: 'This is message 3', user: 'Hiws' }
              ]
            }
          }
        })
        <script src="https://unpkg.com/vue@2.6.11/dist/vue.min.js"></script>
        <script src="https://unpkg.com/bootstrap-vue@2.5.0/dist/bootstrap-vue.js"></script>
        
        <link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
        <link href="https://unpkg.com/bootstrap-vue@2.5.0/dist/bootstrap-vue.css" rel="stylesheet"/>
        
        <div id="app">
          <!-- Example 1 -->
          <h3>v-model is the only the id</h3>
          <b-select v-model="selected" class="mb-3">
            <b-select-option v-for="{ id, msg } in messages" :key="id" :value="id">
            	{{ msg }}
            </b-select-option>
          </b-select>
          Selected value: {{ selected }}
          
          <hr />
        
          <!-- Example 2 -->
          <h3>v-model is the entire object</h3>
          <b-select v-model="selected2" class="mb-3">
            <b-select-option v-for="message in messages" :key="message.id" :value="message">
            	{{ message.msg }}
            </b-select-option>
          </b-select>
          Selected value: {{ selected2 }}
        </div>

        【讨论】:

        • 喜欢这个解决方案,它看起来是最好的方法 :) 谢谢
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-31
        • 2017-03-08
        • 2022-12-04
        • 2014-10-19
        相关资源
        最近更新 更多