0

Given

const allPost = [{_id: "uniqueId1", "name": "Bob"}, {_id: "uniqueId2", "name": "Sam"}]
const changeTo = {_id: "uniqueId1", "name": "Tim"}

I want to change to the given allPost object so it becomes

const allPost = [{_id: "uniqueId1", "name": "Tim"}, {_id: "uniqueId2", "name": "Sam"}]

I tried this but it does not work

const allPost = [{_id: "uniqueId1", "name": "Bob"}, {_id: "uniqueId2", "name": "Sam"}]
const changeTo = {_id: "uniqueId1", "name": "Tim"}
const newPost = allPost.filter((post) => {
    if(post._id === changeTo._id) {
        post = changeTo
    }

})

Anyway to accomplish this?

name
  • 235
  • 2
  • 12

1 Answers1

0

Ciao, you can use a map function like this:

const allPost = [{_id: "uniqueId1", "name": "Bob"}, {_id: "uniqueId2", "name": "Sam"}]
const changeTo = {_id: "uniqueId1", "name": "Tim"}
const newPost = allPost.map((post) => {
    if(post._id === changeTo._id) return changeTo;
    else return post;
});
console.log(newPost);
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
  • Huh, "you cannot change `allPost` content"? Using the `const` keyword does not make the array immutable. You need to reword that phrase a bit. – KarelG Aug 12 '20 at 06:48
  • As simpler as better... anyway if you try on snippet to make the map directly in const allPost you will get an error "you cannot change a const"... – Giovanni Esposito Aug 12 '20 at 06:50