Src
Src

Reputation: 5482

Grab a property of an object

I have an object comments. It can be undefined in some cases and in the other cases it looks like

{
  id: 1,
  ...,
  next_page: 'someurl' // can also be undefined in some cases
}

I need to grab that next_page property if it exist or make it null in other cases. My code:

let next_page = null;

if (comments && comments.next_page)
  next_page = comments.next_page

It works, but i'm feeling like there is some easier way. Am i right?

Upvotes: 0

Views: 49

Answers (3)

Perspective
Perspective

Reputation: 632

If the property is missing maybe you can have a template object and won't have to assign it.

const template = { id: null, nextPage: nul};
const useThis = Object.assign({}, template, dataMaybeHasNextPage)

// if dataMaybeHasNextPage object has nextPage then useThis.nextPage would a url

That way nextPage would always be set.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

const defaultCommentObj = { id: null, nextPage: null};
const commentA = Object.assign({}, defaultCommentObj, {
  id: 1,
  nextPage: 'https://google.com',
});

const commentB = Object.assign({}, defaultCommentObj, {
  id: 2,
});

console.log('A : ', commentA);
console.log('B : ', commentB);

Upvotes: 0

trueter
trueter

Reputation: 126

Does it have to be null? If so, go with:

const next_page = comments && comment.next_page || null

If undefined is fine as well, I'd suggest:

const next_page = comments && comment.next_page

Javascript is behaving a bit unexpectedly here. The result of the expression right of the equals sign is undefined if next_page does not exist on comment, but comment.next_page if it does exist.

Edit: As pointed out in a different comment: be careful when next_page is a falsy value as version #1 will return null, when comment.next_page is 0.

Upvotes: 2

user2065722
user2065722

Reputation: 1

The expression in the if() block returns the value of the expression (not boolean), so you can condense it into one line:

let next_page = ( comments && comments.next_page );

Upvotes: 0

Related Questions