2
axios.post('saveUser', {id, name})

If name is empty how could I exclude it in the param? if I put ({id, name}), isn't the method would still have a property of name undefined?

I don't want this

const obj = {id: 123, name: undefined}

I want this const obj = {id: 123}

but I don't want to create a temporary variable like so

let obj = { id: id }; if(name) obj = { ...obj, name };
6
  • 4
    "I don't to create temporary variable like so" why? What's the problem with that? Commented Apr 19, 2021 at 7:48
  • @VLAZ I want to avoid mutable object, avoid let if possible Commented Apr 19, 2021 at 7:50
  • 1
    let is unrelated to mutable objects. It's for a mutable variable. You can do const obj = {id}; if (name) obj[name] = name; and the variable is immutable. The object isn't. Besides it is a very strange requirement. You can determine whether to have a property or not at creation time but it's usually not worth doing that. If you're creating the object right now, it doesn't really matter whether you're treating it mutably or not - assuming you're doing this in a function, it's still a pure operation. Commented Apr 19, 2021 at 7:54
  • If your server is not able to handle unpredictable data in id or name you have other problems than a superfluous property. Commented Apr 19, 2021 at 7:55
  • ok I just don't want temporary variable and see if there's a better way to handle this case. Commented Apr 19, 2021 at 8:56

2 Answers 2

4

I would suggest you adding object properties conditionally with ES6 syntax like this.

const normalizeData = ({id, name = ""}) => {
  const condition = !!name; // Equivalent to: name !== undefined && name !== "";
  return {id, ...(condition && { name })};
} 
console.log(normalizeData({id: 123, name: ""}));
console.log(normalizeData({id: 123, name: undefined}));
console.log(normalizeData({id: 123, name: "Phong_Nguyen"}));

Explain:

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

8 Comments

Could you change the first case so that it states an undefined name: console.log(normalizeData({id: 123, name: undefined}));?
I've just updated, Pls take a look at it @chrwahl Pls let me know if it works.
That was exactly it @Nguyễn-Văn-Phong
nice. the answer is actually at this line {id, ...(name && { name })}; correct? there's typo of double ; at the end.
@NguyễnVănPhong this is genius! it's way better than creating a temp variable!
|
1

You can create the object with the id first and then add a name afterwards:

const obj = {id: 123};
if(name) obj.name = name;
axios.post('saveUser', obj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.