Shaoz
Shaoz

Reputation: 10653

In Ember, how to get all the properties of an object from an Array by checking one key/value

I have an array of objects of products. But I want to grab just one object in the array to do something with it, by checking a property value of that object if it's true.

I'm not sure if I'm doing it correctly. How can I do that the Ember way.

Can someone help me, please. Thank you!

Model:

// model
import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  sku: DS.attr('number'),
  price: DS.attr('number'),
  createdAt: DS.attr('date')
});

Controller:

// controller
import Ember from 'ember';

export default Ember.Controller.extend({
  store: Ember.inject.service(),

  products: Ember.computed('store', function () {
    return this.get('store').findAll('product').then(product => product);
  }),

  actions: {
    selectProduct(value) {
      // I'm not sure if this is the correct way of grab an object
      this.get('products').filter((product) => {

        if (product.get('name') === value) {
          let newProduct = Ember.Object.create({
            name: product.get('name'),
            description: product.get('description'),
            price: product.get('price')
          });

          return newProduct;
        } else {
          console.log('Please select something!!');
        }
      });
    }
  }
});

Template:

// template
<div class="product-list">
  <select id="prod-list" onchange={{action "selectProduct" value="target.value"}}>
    {{#each products as |product|}}
      <option value="{{product.name}}">{{product.name}}</option>
    {{/each}}
  </select>
</div>

Upvotes: 0

Views: 173

Answers (1)

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9406

At first, it's better to fetch data in route.

You can use findBy method to find an item.

Please take a look at this twiddle.

I changed the adapter to fake data.

Upvotes: 1

Related Questions