0

How can I obtain one of these objects by using the filter or find method and looking for a match inside of the fiberAgrupations Array

I tried doing this:

const landlineRate = this.monolineJsonRates[0].cambioCaudal.getAll()
    .filter(landlinedRates => landlinedRates["fiberAgrupations"].includes(this.myPackId));

myPackId is 3230 which is in the first object.

JSON:

         [{
            "id": "T300Mb2",
            "idAdditionalImage": "",
            "name": "300 Mb",
            "sourceId": ["T300Mb2"],
            "fiberAgrupations": ["3230","3232","3234","3235","3237","3239","3248","3250","2875","2877","3139","3140","3074","3075"],
            "prices": [
              {"id": "3149", "price": "34,95"},
              {"id": "3156", "price": "39,95"},
            ],
            "availableRates": ["T600Mb2", "T1Gb"]
         },
         {
            "id": "T600Mb",
            "idAdditionalImage": "",
            "name": "600 Mb",
            "sourceId": ["T600Mb"],
            "fiberAgrupations": ["2989","2994","2982","2983","3090","3089","3093","3084","2875","2877","3139","3140","3074","3075"],
            "prices": [
              {"id": "3149", "price": "38,95"},
              {"id": "3156", "price": "47,95"},
            ],
            "availableRates": []
         },
         {
            "id": "T600Mb2",
            "idAdditionalImage": "",
            "name": "600 Mb",
            "sourceId": ["T600Mb2"],
            "fiberAgrupations": ["3219","3220","3223","3224","3241","3244","3252","3255","2875","2877","3139","3140","3074","3075"],
            "prices": [
              {"id": "3149", "price": "38,95"},
              {"id": "3156", "price": "43,95"},
            ],
            "availableRates": ["T1Gb"]
         }],

1 Answer 1

1

Find will give you first element in the provided array that satisfies the provided testing function. Filter will give you a new array with all elements in the provided array that satisfies the provided testing function.

Simplified:

const rates = [{
    'id': 'T300Mb2',
    'fiberAgrupations': ['3230', '3232']
  },
  {
    'id': 'T600Mb',
    'fiberAgrupations': ['2989', '2994']
  },
  {
    'id': 'T600Mb2',
    'fiberAgrupations': ['3219', '3220'],
  }];

const myPackId = '3230';
const result = rates.filter(landlinedRates =>
 landlinedRates['fiberAgrupations'].includes(myPackId)
);
console.log(result);

gives:

[ 
   { 
    id: 'T300Mb2', 
    fiberAgrupations: [ '3230', '3232' ]
   } 
]
Sign up to request clarification or add additional context in comments.

3 Comments

This returns an empty array just like the solution I tried myself
Are u sure the getAll method is returning the results? Can it be that the getAll function is an async function?
My JSON wasnt being deserialized correctly... my solution does work, sorry for the mess up

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.