Search code examples
javascriptarraysjavascript-objects

How to modify a value in array of object's based on other object


i have an object as :

let sample = {cat: 10 , dog: 50 , snake: 25};

I have the array of object as :

let petarray = [
    {name: 'newcat' , quantity: 20},
    {name: 'oldcat' , quantity: 15},
    {name: 'razordog' , quantity: 10}
];

May I know how can I modify the petarray quantity such that if petarray[allindexes].name includes any of sample , then quantity = quantity * (respective number of sample )

for eg: petarray[0].name includes cat , the quantity should be modified as 20*(10)

any help on how to achieve is much appreciated ,TIA (hope it is clear)

  • please let me know for any more info or on what i can do to improve about this result

Solution

  • you can try this,

    let sample = {cat: 10 , dog: 50 , snake: 25};
    let petarray = [{name: 'newcat' , quantity: 20},{name: 'oldcat' , quantity: 15},{name: 'razordog' , quantity: 10}];
    let sampleArrayKeys = Object.keys(sample)
    petarray = petarray.map((p) =>{
     const key = sampleArrayKeys.find(sak => p.name.includes(sak))
     if (key) {
      p.quantity *= sample[key]
     }
     return p
    })
    
    console.log(petarray)