首页 > 解决方案 > 为什么 find 函数在比较 Vue 中的两个数据属性时不起作用?

问题描述

IdofstateGDPrankof的值statesJson相等时,它们应该显示为输出。但是有一些我没有得到的错误。

var app = new Vue({
  el: "#app",
  data(){
    return {
    statesJson:{
"type": "FeatureCollection",
"features": [{ "rank":"1", "NAME_1": "Andaman and Nicobar"},
             { "rank":"2", "NAME_1": "Rajasthan"},
             { "rank":"3", "NAME_1": "Orissa"}]
    },
    
    stateGDP:[{ "Id":"1", "NAME_1": "Andaman and Nicobar","2000":"48"},
             { "Id":"2", "NAME_1": "Rajasthan","2000":"87"},
             { "Id":"3", "NAME_1": "Orissa","2000":"25"}]
    }
  },
   computed:{ 
    check(){
      let x = this.statesJson.features.map(feature =>{ return feature.rank})
      let stateData = this.stateGDP.find(state => state.Id === x)
      return x
    }
  }
 })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div v-for="state in check">
       {{state}}
    </div>
</div>

标签: javascripthtmlvue.js

解决方案


这是因为 map 返回一个数组。要修复您的代码,您所要做的就是检查是否x包含您的 id。

var app = new Vue({
  el: "#app",
  data() {
    return {
      statesJson: {
        "type": "FeatureCollection",
        "features": [
          { "rank":"1", "NAME_1": "Andaman and Nicobar"},
          { "rank":"2", "NAME_1": "Rajasthan"},
          { "rank":"3", "NAME_1": "Orissa"},
        ]
      },
    
      stateGDP: [
        { "Id":"1", "NAME_1": "Andaman and Nicobar","2000":"48"},
        { "Id":"2", "NAME_1": "Rajasthan","2000":"87"},
        { "Id":"3", "NAME_1": "Orissa","2000":"25"},
      ],   
    }
  },
  computed:{ 
    check(){
      let state = this.statesJson.features.map(feature => {
        return this.stateGDP.find(state => state.Id === feature.rank);
      });
      
      return state;
    }
  },
 })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <strong>Total object</strong><hr/>
  <div v-for="state in check">
    {{ state }}
  </div>
  
  <br/>
  
  <strong>Seperate variables</strong><hr/>
  <div v-for="state in check">
    Id = {{ state["Id"] }}<br/>
    Name_1 = {{ state["NAME_1"] }}<br/>
    2000 = {{ state["2000"] }}
  </div>
</div>


推荐阅读