Angular2-来自另一个数组的对象数组

时间:2017-06-29 14:18:24

标签: javascript arrays

我有两个对象数组。我试过array.filter但是无法从数组内部过滤数组。

注意:OPTIONGROUP数组项是动态的。

数组1:

0:[{CATEGORYNAME:"Scrub Pants"
CATEGORY_ID:2
DESCRIPTION:null
IMAGE_URL_1:"http://www.pulseuniform.com/stylepic/AD-2513.jpg"
IMAGE_URL_2:"http://www.pulseuniform.com/stylepic/AD-2513.jpg"
IMAGE_URL_3:"http://www.pulseuniform.com/stylepic/AD-2513.jpg"
IMAGE_URL_4:"http://www.pulseuniform.com/stylepic/AD-2513.jpg"
NUM_OF_ORDERS:16
NUM_WISH_LIST:"100"
OPTIONGROUP:[
     {
      BRAND:'Adar Medical Uniforms'
      COLOR:'ASP:Asparagus'
      PRICE:'11.19'
      SIZE:'2XL'
      },
     {
      BRAND:'Adar Medical Uniforms'
      COLOR:'ASP:Asparagus'
      PRICE:'16.19'
      SIZE:'4XL'
      }],
PRICE: 175
PRODUCT_ID:17497
SALE_PRICE:11.19
SELLERNAME:"Adar Medical Uniforms"
SHORT_DESCRIPTION:"Adar Universal Unisex Natural-Rise Five Pocket Drawstring Tapered Leg Pants"
STYLECODE:"AD-2513"
STYLENAME:"Adar Universal Unisex Natural-Rise Five Pocket Drawstring Tapered Leg Pants"
THUMB_IMAGE_URL:"http://www.pulseuniform.com/stylepic/AD-2513.jpg"
VENDORNAME:"Adar"}]

如何从optiongroup中的array2搜索array1项。 下面是我的阵列2

数组2:

{COLOR:[{0:"ASP:Asparagus"},{1:"BRG:Burgundy"}],
SIZE:[{0:"M"}] }

1 个答案:

答案 0 :(得分:0)

可能有一种更有效的方法,但这里有一个使用Array.filter()和多次迭代的工作示例的小提琴。

https://jsfiddle.net/gmedyh6s/

我不得不简化你的搜索参数结构

interface SearchParams = {
  SIZE: Array<string>,
  COLOR: Array<string>
};

const filterMyArray = function(array: Array<any>, searchParams: SearchParams): Array<any> {
  return array.filter( item => {

    // Parsing every search param
    return Object.keys(searchParams).map( param => {

        // Getting the array of params of the current item
        let itemOptions = item.OPTIONGROUP.map( option => option[param] );

        // Search param is contained in the considered array ?
        return searchParams[param].every( elem => itemOptions.indexOf(elem) > -1 );
    })

    // At this point we have an array of boolean, flattening it --> Must be true everywhere
    .reduce( (total,item) => {
            return total && item;
    }, true);

  });
}

const array: Array<any> = [ ... ];

const filtered = filterMyArray( array, {
  SIZE:['2XL'],
  COLOR:['ASP:Asparagus']
} );