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?

0

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Huh, "you cannot change allPost content"? Using the const keyword does not make the array immutable. You need to reword that phrase a bit.
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"...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.