Reputation: 605
I'm converting some objects to JSON:
const tpL = results.map(post => ({
...post.toJSON(),
postid: post.get("comment").id,
commentid: post.get("post").id
}));
But post.get("comment")
or post.get("post")
is not defined in every obejct. So I have to check if post.get("comment")
is exist first.
How can I do that?
Upvotes: 0
Views: 57
Reputation: 1260
The other answers work and are elegant but you might miss that you can also use a full block of code as the body of the function you pass to map()
and not just an expression (which ({ /*code omitted*/ })
) is. So you could also write
const tpL = results.map(post => {
const res = post.toJSON();
if (post.get("comment")){
res.postid = post.get("comment").id;
}
if (post.get("post")){
res.commentid = post.get("post").id;
}
return res;
});
Upvotes: 1
Reputation: 7615
Since Optional Chaining is not supported in every environments nor every Browsers, I'd suggest you to do as follow:
const tpL = results.map(post => ({
...post.toJSON(),
...(post.get("comment") && { postid: post.get("comment").id }),
...(post.get("post") && { commentid: post.get("post").id })
}));
This way the objects of the array will contain the postid
only if .get("comment")
is defined and the commentid
only if .get('post')
is defined.
Upvotes: 2
Reputation: 56
const tpL = results.map(post => ({
...post.toJSON(),
postid: post.get("comment") ? post.get("comment").id : null,
commentid: post.get("post") ? post.get("post").id : null
}));
PS note the return value adjusts to your defaults This is similar to the solution above but allows you to set defaults
Upvotes: 1
Reputation: 371233
This sounds like a great use case for optional chaining:
const tpL = results.map(post => ({
...post.toJSON(),
postid: post.get("comment")?.id,
commentid: post.get("post")?.id
}));
If the .get
returns null or undefined, the resulting property value will undefined
.
This is relatively new syntax, so it's not supported everywhere yet. (if you're putting this on a public website, hopefully your script is already being transpiled with Babel for cross-browser compatibility)
Upvotes: 5