代码之家  ›  专栏  ›  技术社区  ›  Onyx

尝试迭代对象数组,并创建一个新属性,该属性包含来自该句子文本属性的单词数组

  •  1
  • Onyx  · 技术社区  · 3 年前

    sentences: [
        {
            text: "Go away and hide behind that door where we found you just now.",
            grade: 606
        },
        {
            text: "Please don't let anyone spoil these nice fresh flowers.",
            grade: 609
        },
    ]
    

        mounted(){
            this.sentences.map((sentence) => {
                const arrayOfWords = sentence.text.split(' ');
                sentence.words = arrayOfWords
            })
            console.log(this.sentences)
        }
    
    2 回复  |  直到 3 年前
        1
  •  1
  •   Majed Badawi    3 年前

    Array#map

    this.sentences

    new Vue({
      el: "#app",
      data: () => ({
        sentences: [
          { text: "Go away and hide behind that door where we found you just now.", grade: 606 },
          { text: "Please don't let anyone spoil these nice fresh flowers.", grade: 609 }
        ]
      }),
      mounted(){
        this.sentences = this.sentences.map(sentence => {
          const arrayOfWords = sentence.text.split(' ');
          sentence.words = arrayOfWords
          return sentence;
        })
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
      <div v-for="(sentence, i) in sentences" :key="i">{{sentence.words}}</div>
    </div>

    computed property

    new Vue({
      el: "#app",
      data: () => ({
        sentences: [
          { text: "Go away and hide behind that door where we found you just now.", grade: 606 },
          { text: "Please don't let anyone spoil these nice fresh flowers.", grade: 609 }
        ]
      }),
      computed: {
        sentencesWithWords: function() {
          return this.sentences.map(sentence => {
            const arrayOfWords = sentence.text.split(' ');
            sentence.words = arrayOfWords
            return sentence;
          });
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
      <div v-for="(sentence, i) in sentencesWithWords" :key="i">{{sentence.words}}</div>
    </div>
        2
  •  0
  •   ABDULLOKH MUKHAMMADJONOV    3 年前

    Array.map() this.sentences forEach() 要更改原始数组,请执行以下操作:

    mounted(){
        this.sentences.forEach(sentence => {
             const arrayOfWords = sentence.text.split(' ');
             sentence.words = arrayOfWords
        })
        console.log(this.sentences)
    }
    

    mounted(){
        this.sentences = this.sentences.map(sentence => {
             sentence.words = sentence.text.split(' ');
             return sentence
        })
        console.log(this.sentences)
    }