0

I want to loop through the allData and search if the id matches 12345, I want to remove the Offer Object and insert the newOffer Object

$(document).ready(function () {
    var newOfferToInsert = {
        "id":   "12345",
        "name": "ssfd Offer"
    }

    var idToSearch = '12345'

    var allData = [{
        "id": {
            "Street": "555 92nd St S",
            "id": "12345"
        },
        "Offer": {
            "id": "12345"
        }
    }, {
        "id": {
            "Street": "666 DFTYY",
            "id": "345"
        },
        "Offer": {
            "id": "345"
        }
    }];
});

https://jsfiddle.net/9avwsm1p/

Daan
  • 2,680
  • 20
  • 39
Lavanya
  • 115
  • 5

3 Answers3

3

You can do it like this:

allData.forEach(function(cartObj) {
    if(cartObj.id.id === idToSearch){   
        cartObj.Offer = newOfferToInsert;
    }
});
Dom
  • 31
  • 1
0

const newOfferToInsert = {
  "id": "12345",
  "name": "ssfd Offer"
}

const idToSearch = '12345'

const allData = [{
  "id": {
    "Street": "555 92nd St S",
    "id": "12345"
  },
  "Offer": {
    "id": "12345"
  }
}, {
  "id": {
    "Street": "666 DFTYY",
    "id": "345"
  },
  "Offer": {
    "id": "345"
  }
}];


console.log(replaceOffer(allData, idToSearch, newOfferToInsert))

function replaceOffer(allData, idToSearch, newOfferToInsert) {
  return allData.map(element => {
    if (element.Offer.id === idToSearch) {
      element.Offer = newOfferToInsert
    }
    return element
  })
}
David Alvarez
  • 1,226
  • 11
  • 23
0
    var newOfferToInsert = {
    "id":   "12345",
    "name": "ssfd Offer"
}

var idToSearch = '12345'

var allData = [{
    "id": {
        "Street": "555 92nd St S",
        "id": "12345"
    },
    "Offer": {
        "id": "12345"
    }
}, {
    "id": {
        "Street": "666 DFTYY",
        "id": "345"
    },
    "Offer": {
        "id": "345"
    }
}];

allData.forEach((obj)=>{

if(obj.Offer.id===idToSearch)
{
    obj.Offer=newOfferToInsert

}

})

console.log(allData)

Rajib
  • 24
  • 4