Reputation: 491
I have a function where it receives an object (called "card"). inside this function i wanna change the value of one of its properties but it doesn't change. here is the function:
function replaceImgsUrl(card){
console.log("card: " , card);// prints card: {imgs:[]}
card.imgs = "sex";
console.log("new card: " , card); // prints new card: {imgs:[]}
return card;
}
By the way i am using node.js , although i don't think it would make a difference. Does anyone have an idea on why this could be happening?
Upvotes: 1
Views: 2288
Reputation: 31024
I'm not sure how your card
object was defined and if it was freezed
or you are using some kind of immutable library which will prevent you from mutating properties.
But otherwise it works fine as you can see here:
var myCard = {
imgs: []
}
function replaceImgsUrl(card){
console.log("card: " , card);// prints card: {imgs:[]}
card.imgs = "sex";
console.log("new card: " , card); // prints new card: {imgs:[]}
return card;
}
replaceImgsUrl(myCard);
Upvotes: 2
Reputation: 351328
It looks like the card
object was frozen with Object.freeze()
or otherwise configured to not allow modifications to the object properties.
If you really want the imgs
property to change from an array to a string, then you'd probably have no other way than to create a new object:
function replaceImgsUrl(card){
console.log("card: " , card);// prints card: {imgs:[]}
card = Object.assign({}, card); // get shallow copy
card.imgs = "sex";
console.log("new card: " , card); // prints new card: {imgs:"sex"}
return card;
}
Note that only the returned value will have the object as you want it; the original object will not have changed.
Upvotes: 0
Reputation: 3487
Your code seems working with an actual object as argument but looks strange. Why do you want to replace an object property which type is an array by a string ?
function replaceImgsUrl(card){
console.log("card: " , card);// prints card: {imgs:[]}
// card.imgs = "sex";
card.imgs.push("sex"); // Isn't it what you'd like to do ?
console.log("new card: " , card); // prints new card: {imgs:[]}
return card;
}
replaceImgsUrl({ imgs: [] });
Upvotes: 0