2016-05-18 2 views
-2

Javascript новичок здесь :) Я хочу достичь sth, но не могу понять это.Создание массива массивов без дублирования Javascript

Вот мои данные.

<pre> 
[ 
    [ 
    { 
     "id": 2759178563, 
     "title": "Ergonomic Paper Computer", 
     "handle": "ergonomic-paper-computer", 
     "body_html": "Enable turn-key infrastructures", 
     "published_at": "2015-09-23T20:51:49-04:00", 
     "created_at": "2015-09-23T20:51:49-04:00", 
     "updated_at": "2015-09-23T20:51:49-04:00", 
     "vendor": "Schinner Inc", 
     "product_type": "Computer", 
     "tags": [ 
     "Computer", 
     "Ergonomic", 
     "Paper" 
     ], 
     "variants": [ 
     { 
      "id": 8041863299, 
      "title": "White", 
      "option1": "White", 
      "option2": null, 
      "option3": null, 
      "price": "67.25", 
      "grams": 5145, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 1, 
      "product_id": 2759178563, 
      "created_at": "2015-09-23T20:51:49-04:00", 
      "updated_at": "2015-09-23T20:51:49-04:00", 
      "available": true, 
      "featured_image": null 
     }, 
     { 
      "id": 8041863363, 
      "title": "Mint green", 
      "option1": "Mint green", 
      "option2": null, 
      "option3": null, 
      "price": "29.58", 
      "grams": 6860, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 2, 
      "product_id": 2759178563, 
      "created_at": "2015-09-23T20:51:49-04:00", 
      "updated_at": "2015-09-23T20:51:49-04:00", 
      "available": true, 
      "featured_image": null 
     }, 
     { 
      "id": 8041863491, 
      "title": "Yellow", 
      "option1": "Yellow", 
      "option2": null, 
      "option3": null, 
      "price": "54.19", 
      "grams": 6045, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 3, 
      "product_id": 2759178563, 
      "created_at": "2015-09-23T20:51:49-04:00", 
      "updated_at": "2015-09-23T20:51:49-04:00", 
      "available": true, 
      "featured_image": null 
     }, 
     { 
      "id": 8041863555, 
      "title": "Blue", 
      "option1": "Blue", 
      "option2": null, 
      "option3": null, 
      "price": "22.88", 
      "grams": 9526, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 4, 
      "product_id": 2759178563, 
      "created_at": "2015-09-23T20:51:49-04:00", 
      "updated_at": "2015-09-23T20:51:49-04:00", 
      "available": true, 
      "featured_image": null 
     } 
     ], 
     "images": [ 
     { 
      "id": 5642046019, 
      "created_at": "2015-09-23T20:51:49-04:00", 
      "position": 1, 
      "updated_at": "2015-09-23T20:51:49-04:00", 
      "product_id": 2759178563, 
      "variant_ids": [], 
      "src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Ergonomic_20Paper_20Computer.png?v=1443055909" 
     } 
     ], 
     "options": [ 
     { 
      "name": "Title", 
      "position": 1, 
      "values": [ 
      "White", 
      "Mint green", 
      "Yellow", 
      "Blue" 
      ] 
     } 
     ] 
    }, 
    { 
     "id": 2759192387, 
     "title": "Heavy Duty Concrete Keyboard", 
     "handle": "heavy-duty-concrete-keyboard", 
     "body_html": "Strategize synergistic e-markets", 
     "published_at": "2015-09-23T20:52:07-04:00", 
     "created_at": "2015-09-23T20:52:07-04:00", 
     "updated_at": "2015-09-23T20:52:07-04:00", 
     "vendor": "Stiedemann and Sons", 
     "product_type": "Keyboard", 
     "tags": [ 
     "Concrete", 
     "Duty", 
     "Heavy", 
     "Keyboard" 
     ], 
     "variants": [ 
     { 
      "id": 8041883779, 
      "title": "Magenta", 
      "option1": "Magenta", 
      "option2": null, 
      "option3": null, 
      "price": "14.20", 
      "grams": 3030, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 1, 
      "product_id": 2759192387, 
      "created_at": "2015-09-23T20:52:07-04:00", 
      "updated_at": "2015-09-23T20:52:07-04:00", 
      "available": true, 
      "featured_image": null 
     } 
     ], 
     "images": [ 
     { 
      "id": 5642056899, 
      "created_at": "2015-09-23T20:52:07-04:00", 
      "position": 1, 
      "updated_at": "2015-09-23T20:52:07-04:00", 
      "product_id": 2759192387, 
      "variant_ids": [], 
      "src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Heavy_20Duty_20Concrete_20Keyboard.png?v=1443055927" 
     } 
     ], 
     "options": [ 
     { 
      "name": "Title", 
      "position": 1, 
      "values": [ 
      "Magenta" 
      ] 
     } 
     ] 
    } 
    ], 
    [ 
    { 
     "id": 2759168323, 
     "title": "Awesome Cotton Computer", 
     "handle": "awesome-cotton-computer-1", 
     "body_html": "Brand synergistic applications", 
     "published_at": "2015-09-23T20:51:24-04:00", 
     "created_at": "2015-09-23T20:51:24-04:00", 
     "updated_at": "2015-09-23T20:51:24-04:00", 
     "vendor": "Hills Group", 
     "product_type": "Computer", 
     "tags": [ 
     "Awesome", 
     "Computer", 
     "Cotton" 
     ], 
     "variants": [ 
     { 
      "id": 8041841795, 
      "title": "Black", 
      "option1": "Black", 
      "option2": null, 
      "option3": null, 
      "price": "2.05", 
      "grams": 1906, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 1, 
      "product_id": 2759168323, 
      "created_at": "2015-09-23T20:51:24-04:00", 
      "updated_at": "2015-09-23T20:51:24-04:00", 
      "available": true, 
      "featured_image": null 
     }, 
     { 
      "id": 8041841859, 
      "title": "Orchid", 
      "option1": "Orchid", 
      "option2": null, 
      "option3": null, 
      "price": "10.78", 
      "grams": 4970, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 2, 
      "product_id": 2759168323, 
      "created_at": "2015-09-23T20:51:24-04:00", 
      "updated_at": "2015-09-23T20:51:24-04:00", 
      "available": true, 
      "featured_image": null 
     }, 
     { 
      "id": 8041841923, 
      "title": "Tan", 
      "option1": "Tan", 
      "option2": null, 
      "option3": null, 
      "price": "50.54", 
      "grams": 6738, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 3, 
      "product_id": 2759168323, 
      "created_at": "2015-09-23T20:51:24-04:00", 
      "updated_at": "2015-09-23T20:51:24-04:00", 
      "available": true, 
      "featured_image": null 
     }, 
     { 
      "id": 8041841987, 
      "title": "Teal", 
      "option1": "Teal", 
      "option2": null, 
      "option3": null, 
      "price": "91.51", 
      "grams": 8718, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 4, 
      "product_id": 2759168323, 
      "created_at": "2015-09-23T20:51:24-04:00", 
      "updated_at": "2015-09-23T20:51:24-04:00", 
      "available": true, 
      "featured_image": null 
     }, 
     { 
      "id": 8041842051, 
      "title": "Gold", 
      "option1": "Gold", 
      "option2": null, 
      "option3": null, 
      "price": "8.24", 
      "grams": 194, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 5, 
      "product_id": 2759168323, 
      "created_at": "2015-09-23T20:51:24-04:00", 
      "updated_at": "2015-09-23T20:51:24-04:00", 
      "available": true, 
      "featured_image": null 
     } 
     ], 
     "images": [ 
     { 
      "id": 5642032131, 
      "created_at": "2015-09-23T20:51:24-04:00", 
      "position": 1, 
      "updated_at": "2015-09-23T20:51:24-04:00", 
      "product_id": 2759168323, 
      "variant_ids": [], 
      "src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Awesome_20Cotton_20Computer_f74fc2a4-efa5-42ca-a3b2-36c378f1c003.png?v=1443055884" 
     } 
     ], 
     "options": [ 
     { 
      "name": "Title", 
      "position": 1, 
      "values": [ 
      "Black", 
      "Orchid", 
      "Tan", 
      "Teal", 
      "Gold" 
      ] 
     } 
     ] 
    }, 
    { 
     "id": 2759192387, 
     "title": "Heavy Duty Concrete Keyboard", 
     "handle": "heavy-duty-concrete-keyboard", 
     "body_html": "Strategize synergistic e-markets", 
     "published_at": "2015-09-23T20:52:07-04:00", 
     "created_at": "2015-09-23T20:52:07-04:00", 
     "updated_at": "2015-09-23T20:52:07-04:00", 
     "vendor": "Stiedemann and Sons", 
     "product_type": "Keyboard", 
     "tags": [ 
     "Concrete", 
     "Duty", 
     "Heavy", 
     "Keyboard" 
     ], 
     "variants": [ 
     { 
      "id": 8041883779, 
      "title": "Magenta", 
      "option1": "Magenta", 
      "option2": null, 
      "option3": null, 
      "price": "14.20", 
      "grams": 3030, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 1, 
      "product_id": 2759192387, 
      "created_at": "2015-09-23T20:52:07-04:00", 
      "updated_at": "2015-09-23T20:52:07-04:00", 
      "available": true, 
      "featured_image": null 
     } 
     ], 
     "images": [ 
     { 
      "id": 5642056899, 
      "created_at": "2015-09-23T20:52:07-04:00", 
      "position": 1, 
      "updated_at": "2015-09-23T20:52:07-04:00", 
      "product_id": 2759192387, 
      "variant_ids": [], 
      "src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Heavy_20Duty_20Concrete_20Keyboard.png?v=1443055927" 
     } 
     ], 
     "options": [ 
     { 
      "name": "Title", 
      "position": 1, 
      "values": [ 
      "Magenta" 
      ] 
     } 
     ] 
    } 
    ], 
    [ 
    { 
     "id": 2759167747, 
     "title": "Awesome Bronze Computer", 
     "handle": "awesome-bronze-computer", 
     "body_html": "Orchestrate holistic web services", 
     "published_at": "2015-09-23T20:51:20-04:00", 
     "created_at": "2015-09-23T20:51:20-04:00", 
     "updated_at": "2015-09-23T20:51:20-04:00", 
     "vendor": "Zboncak-Kemmer", 
     "product_type": "Computer", 
     "tags": [ 
     "Awesome", 
     "Bronze", 
     "Computer" 
     ], 
     "variants": [ 
     { 
      "id": 8041840195, 
      "title": "Magenta", 
      "option1": "Magenta", 
      "option2": null, 
      "option3": null, 
      "price": "56.69", 
      "grams": 6035, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 1, 
      "product_id": 2759167747, 
      "created_at": "2015-09-23T20:51:20-04:00", 
      "updated_at": "2015-09-23T20:51:20-04:00", 
      "available": true, 
      "featured_image": null 
     }, 
     { 
      "id": 8041840259, 
      "title": "Mint green", 
      "option1": "Mint green", 
      "option2": null, 
      "option3": null, 
      "price": "63.89", 
      "grams": 9961, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 2, 
      "product_id": 2759167747, 
      "created_at": "2015-09-23T20:51:20-04:00", 
      "updated_at": "2015-09-23T20:51:20-04:00", 
      "available": true, 
      "featured_image": null 
     }, 
     { 
      "id": 8041840323, 
      "title": "Maroon", 
      "option1": "Maroon", 
      "option2": null, 
      "option3": null, 
      "price": "18.76", 
      "grams": 922, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 3, 
      "product_id": 2759167747, 
      "created_at": "2015-09-23T20:51:20-04:00", 
      "updated_at": "2015-09-23T20:51:20-04:00", 
      "available": true, 
      "featured_image": null 
     }, 
     { 
      "id": 8041840387, 
      "title": "Salmon", 
      "option1": "Salmon", 
      "option2": null, 
      "option3": null, 
      "price": "97.60", 
      "grams": 1355, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 4, 
      "product_id": 2759167747, 
      "created_at": "2015-09-23T20:51:20-04:00", 
      "updated_at": "2015-09-23T20:51:20-04:00", 
      "available": true, 
      "featured_image": null 
     } 
     ], 
     "images": [ 
     { 
      "id": 5642031235, 
      "created_at": "2015-09-23T20:51:20-04:00", 
      "position": 1, 
      "updated_at": "2015-09-23T20:51:20-04:00", 
      "product_id": 2759167747, 
      "variant_ids": [], 
      "src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Awesome_20Bronze_20Computer.png?v=1443055880" 
     } 
     ], 
     "options": [ 
     { 
      "name": "Title", 
      "position": 1, 
      "values": [ 
      "Magenta", 
      "Mint green", 
      "Maroon", 
      "Salmon" 
      ] 
     } 
     ] 
    }, 
    { 
     "id": 2759192387, 
     "title": "Heavy Duty Concrete Keyboard", 
     "handle": "heavy-duty-concrete-keyboard", 
     "body_html": "Strategize synergistic e-markets", 
     "published_at": "2015-09-23T20:52:07-04:00", 
     "created_at": "2015-09-23T20:52:07-04:00", 
     "updated_at": "2015-09-23T20:52:07-04:00", 
     "vendor": "Stiedemann and Sons", 
     "product_type": "Keyboard", 
     "tags": [ 
     "Concrete", 
     "Duty", 
     "Heavy", 
     "Keyboard" 
     ], 
     "variants": [ 
     { 
      "id": 8041883779, 
      "title": "Magenta", 
      "option1": "Magenta", 
      "option2": null, 
      "option3": null, 
      "price": "14.20", 
      "grams": 3030, 
      "compare_at_price": null, 
      "sku": "", 
      "requires_shipping": true, 
      "taxable": true, 
      "position": 1, 
      "product_id": 2759192387, 
      "created_at": "2015-09-23T20:52:07-04:00", 
      "updated_at": "2015-09-23T20:52:07-04:00", 
      "available": true, 
      "featured_image": null 
     } 
     ], 
     "images": [ 
     { 
      "id": 5642056899, 
      "created_at": "2015-09-23T20:52:07-04:00", 
      "position": 1, 
      "updated_at": "2015-09-23T20:52:07-04:00", 
      "product_id": 2759192387, 
      "variant_ids": [], 
      "src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Heavy_20Duty_20Concrete_20Keyboard.png?v=1443055927" 
     } 
     ], 
     "options": [ 
     { 
      "name": "Title", 
      "position": 1, 
      "values": [ 
      "Magenta" 
      ] 
     } 
     ] 
    } 
    ] 
] 
</pre> 

И вот мой код:

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 

@Injectable() 

export class ShopifyService { 

    /** 
    * Initialization 
    */ 
    constructor (
     private http: Http 
    ) {} 

    private shopifyUrl = 'app/heroes.json'; 

    errorMessage: string; 

    /** 
    * Private Methods 
    */ 
    fetchProducts(): Promise<Response> { 
     return this.http.get(this.shopifyUrl) 
      .toPromise() 
      .then(this.extractData) 
      .catch(this.handleError); 
    } 

    private extractData(res: Response) { 
     if (res.status < 200 || res.status >= 300) { 
      throw new Error('Bad response status: ' + res.status); 
     } 
     let body = res.json(); 
     if (body.data) { 
      return body.data; 
     } 
     else if (body.products) { 
      return body.products; 
     } 
     else { 
      return { }; 
     } 
    } 

    private handleError (error: any) { 
     let errMsg = error.message || 'Server error'; 
     console.error(errMsg); 
     return Promise.reject(errMsg); 
    } 

    private filterProducts(list, archetype) { 
     var result = []; 

     for (var i = 0; i < list.length; i++) { 
      if (list[i].product_type === archetype) { 
       result.push(list[i]); 
      } 
     } 
     return result; 
    } 

    /** 
    * Public Methods 
    */ 
    public findProducts(archetypes) { 
     return this.fetchProducts().then(
       products => { 
         var result = [], 
          fetchedResponse = []; 

        for (var i = 0; i < archetypes.length; i++) { 
         fetchedResponse = this.filterProducts(
          products, archetypes[i] 
         ); 
         result = result.concat(fetchedResponse); 
        } 
        return result; 
       }, 
       error => this.errorMessage = <any>error 
      ) 
    } 

    public findSingleProductVariant() { 
     var result = [], 
      j = 0; 

     return this.findVariants().then(
      product => { 
       for (var i = 0; i < product.length; i++) { 
        // console.log(product[i]); 
       } 
      } 
     ); 
     // return result; 
    } 

    findVariants() { 
     return this.findProducts(['Computer', 'Keyboard']).then(
      products => { 
       var result = []; 

       for (var i = 0; i < products.length; i++) { 
        if (products[i].product_type === 'Computer') { 
         for (var j = 0; j < products.length; j++) { 
          if (products[j].product_type === 'Keyboard') { 
           result.push([products[i], products[j]]); 
          } 
         } 
        } 
       } 
       console.log(result); 
       return result; 
      } 
     ) 
    } 
} 

Пока здесь я не добрался до половины что. Массив двухмерных массивов (один из них имеет тип клавиатуры, а другой - тип компьютера).

Это STH как этот ==>

[ 
    [ 
     [Computer_A], 
     [Keyboard_A] 
    ], 
    [ 
     [Computer_B], 
     [Keyboard_A] 
    ], 
    [ 
     [Computer_C], 
     [Keyboard_A] 
    ], 
] 

Теперь каждый из этих объектов имеют свой собственный набор вариантов. Мне нужно изменить мой findSingleProductVariant, чтобы перейти по каждому из этих массивов, выбрать вариант keyboard (в котором у его массива есть поле цены), а также выбрать вариант computer и рассчитать цену. Если цена меньше 1000, она может продолжить выбор другой клавиатуры и компьютера. Но дело в том, что у него не может быть двух одинаковых массивов. например, мы не можем это сделать.

[ 
    ['Computer_A'], ['Keyboard_A'], 
    ['Computer_A'], ['Keyboard_A'], 
] 
+0

не могли бы вы добавить соответствующие данные в ** текстовую форму ** на вопрос? –

+0

Как у некоторых строк с цифрами в нем что-то связано с таблицами или лампами? –

+0

Извините за путаницу Нина :) В моем коде сначала я фильтрую определенные типы продуктов, и после их фильтрации меня интересуют только их цены. Я поставлю часть реальных данных в вопрос. Спасибо, что нашли время –

ответ

-1

Главное, что вы не можете напрямую сравнивать объекты и ожидать соответствующих результатов, например.

['Red Lamp', 'Blue Table'] === ['Red Lamp', 'Blue Table'] 

вернет ложь (Array.indexOf() также не будет работать, как и следовало ожидать, так как он использует строгое сравнение).

Итак, для массива массивов вам нужно будет использовать два вложенных цикла, чтобы перейти к сравнению примитивных значений.

+0

Спасибо Kama. Вложенные циклы помогли мне двигаться дальше, но я все еще застрял, но в другой части :) –

Смежные вопросы