AbreQueVoy
AbreQueVoy

Reputation: 2316

How to get a value using specified key?

There is an array created out of JSON source with use of $.each method. This is what the console says:

$vm0.sailNames;
[Array(24), __ob__: Observer]

(for some reason, jQuery created an Observer)

In the Vue.js dev view it looks this way: Vue.js View

How can I get displayName value passing name as an argument? Is there any Vue.js arrays way to do this?

-- edit: adding some markup:

data() {
    return {
      (...)
      sailNames: [],
      (...)
    }
  },
  methods: {
    someMethod(name) {
      console.log("sailNames: ", this.sailNames);
      let item = this.sailNames.find(s => s.name == name);
      console.log("name (someMethod's arg.): ", name);
      console.log("item: ", item);

    },
    showName: function(e) { // this is the function triggered @click
      (...)
      const sourceElement = e.target.id;
      this.someMethod(sourceElement);
      (...)
    },
    (...)

Console outputs on DOM element click:

sailNames:  [Array(24), __ob__: Observer]
name (someMethod's arg.):  grot
item:  undefined`

DOM elements in the template:

<svg>
(...)
    <g id="sailShapes">
        <path class="rope" d="M 15,589 395,94" />
        <path id="latacz" d="M 160,404 255,391 390,104 z" class="sail" @click="showName" />
        <path class="rope" d="M 30,592 395,179" />
        <path id="grot" d="M 100,519 285,490 330,254 z" class="sail" @click="showName" />
    (...)
    </g>
(...)
</svg>

Upvotes: 0

Views: 338

Answers (1)

Bert
Bert

Reputation: 82459

This will give you the object.

methods:{
  someMethod(name){
    let item=  this.sailNames.find(s => s.name == name)
    if (!item)
      //error

    // use item.displayName in code
  }
}

But also, typically if you are rendering sailNames in your template, you can just pass the entire object to your method.

<ul>
  <li v-for="item in sailNames" @click="someMethod(item)">{{item.name}}</li>
</ul>

and your someMethod becomes

someMethod(item){
  //use item.displayName
}

Edit

For future readers, there was a small bug in the way sailNames was being populated that caused the above methods to not work. With that fixed, everything flew.

Upvotes: 1

Related Questions