Home > Software design >  How to compare Object and array in Javascript?
How to compare Object and array in Javascript?

Time:04-22

In my application I am trying to compared ids of specification and selectedSpecifications. As of now I hardcoded selectedSpecifications id to 0. I am trying to loop over selectedSpecifications array and then check if id matches.

selectedSpecifications  is an array
specification  is an object

I need help to achieve this functionality.

 let val = this.selectedSpecifications.map(specification => {
        
   if (specification.id == this.selectedSpecifications[0].id) {  ----> How can I remove
 hardcoded value `0` and loop over selectedSpecifications array

        return specification.value ;
}
else{
       
}}

CodePudding user response:

Don't map unless you want to remove all the nulls with a filter

Instead filter first

const selSpecID = this.selectedSpecifications[0].id
const vals = this.selectedSpecifications.filter(({id}) => selSpecID === id)
  .map(({value}) => value)

CodePudding user response:

The main point of clarification is the syntax for map and find is arr.map(eachElementInArray => doSomethingWithElement), but it seems like you're trying to reference the specification as an argument (the other way around). Instead, you want something like this:

let val = this.selectedSpecifications.find(selectedSpec => {
   if (selectedSpec.id === specification.id) {
        return selectedSpec.value;
}

If there's only 1 or no matching specification, I would use Array.prototype.find(). Otherwise map() makes sense if there are multiple matching specifications.

As a final note, I would rather use the strict equality operator (===) here just in case the saved id's have different types, which might help you catch a bug.

  • Related