Categories
JavaScript Answers

How to Get a Subset of a JavaScript Object’s Properties?

Sometimes, we may want to get a subset of JavaScript properties from an object.

In this article, we’ll look at ways to get a subset of JavaScript object’s properties to a place where we can use them.

Object Destructuring

The shortest and easiest way to get a subset of a JavaScript object’s properties is to use the object destructuring syntax.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const {
  a,
  b
} = object
const picked = {
  a,
  b
}
console.log(picked)

We have an object with properties a , b , and c .

To get the properties, we can destructure them to assign them to their own variables.

We did that with:

const {
  a,
  b
} = object

Now a is assigned to object.a .

And b is assigned to object.b .

Then we can put them into another object with:

const picked = {
  a,
  b
}

And so picked is:

{a: 1, b: 2}

We can also do destructuring in function parameters.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const pick = ({
  a,
  b
}) => ({
  a,
  b
})
const picked = pick(object);
console.log(picked)

to create a pick function that returns an object with the a and b properties destructured from the object parameter.

So when we call pick with object , we get that picked is the same as before.

Lodash

We can also use Lodash’s pick method to return an object with the given properties.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const picked = _.pick(object, ['a', 'b']);
console.log(picked)

We call pick with the object to extract properties from.

And the array has the property name strings we want to get.

So picked is the same as the other examples.

Array.prototype.reduce

We can use the JavaScript array reduce method to get the properties from an object and put them into another object.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const picked = ['a', 'b'].reduce((resultObj, key) => ({
  ...resultObj,
  [key]: object[key]
}), {});
console.log(picked)

We call reduce on the [‘a’, ‘b’] array which are the property name strings for the properties we want to get from object .

resultObj has the object with the picked properties.

key has the key we want to get from the array.

We return an object with resultObj spread and the key with its corresponding value appended to the end of it.

The 2nd argument of reduce is an empty object so we can spread the properties into it.

And so picked has the same result as before.

Conclusion

We can get a subset of the properties of JavaScript wit destructuring assignment, array reduce , or the Lodash pick method.

Categories
JavaScript Answers

How to Conditionally Add a Member to a JavaScript Object?

Sometimes, we want to conditionally add a member to a JavaScript object.

In this article, we’ll look at how to conditionally add a member to a JavaScript object.

Spread Operator

We can use the spread operator to spread an object into another object conditionally.

For instance, we can write:

const condition = true  
const obj = {  
  ...(condition && {  
    b: 5  
  })  
}  
console.log(obj)

We use the && operator to return the object only when condition is true .

If the object is returned then it’ll be spread into obj .

And so we get:

{b: 5}

as a result.

Instead of using the && operator, we can also use the ternary operator by writing:

const condition = true  
const obj = {  
  ...(condition ? {  
    b: 5  
  } : {})  
}  
console.log(obj)

We return an empty object when condition is false instead of null .

Object.assign

Also, we can use the Object.assign method to merge an object into another object.

For instance, we can write:

const condition = true  
const obj = Object.assign({}, condition ? {  
  b: 5  
} : null)  
console.log(obj)

We have the condition check in the 2nd argument of the Object.assign method.

We return the object only when condition is true .

Otherwise, null is returned.

Since condition is true , we have the same result for obj .

Conclusion

We can add properties to an object conditionally with the spread operator or the Object.assign method.

We can use the ternary operator or && operator to specify what to add given the condition.

Categories
JavaScript Answers

How to Detect Arrow Key Presses in JavaScript?

Sometimes we need to detect the arrow key presses in our JavaScript web apps.

In this article, we’ll look at how to detect arrow key presses in JavaScript.

Use the keyCode Property

We can listen to the keydown event and get the keyCode property from the event object.

For instance, we can write:

document.onkeydown = (e) => {  
  e = e || window.event;  
  if (e.keyCode === 38) {  
    console.log('up arrow pressed')  
  } else if (e.keyCode === 40) {  
    console.log('down arrow pressed')  
  } else if (e.keyCode === 37) {  
    console.log('left arrow pressed')  
  } else if (e.keyCode === 39) {  
    console.log('right arrow pressed')  
  }  
}

to assign the keydown event handler function to the document.onkeydown property.

This lets us listen to the keydown event on the HTML document.

Then we can get the keyCode property from the e event object to see which key is pressed.

38 is the code for the up arrow.

40 is the code for the down arrow.

37 is the code for the left arrow.

And 39 is the code for the right arrow.

Also, we can use the addEventListener method to add the keydown event listener:

document.addEventListener('keydown', (e) => {  
  e = e || window.event;  
  if (e.keyCode === 38) {  
    console.log('up arrow pressed')  
  } else if (e.keyCode === 40) {  
    console.log('down arrow pressed')  
  } else if (e.keyCode === 37) {  
    console.log('left arrow pressed')  
  } else if (e.keyCode === 39) {  
    console.log('right arrow pressed')  
  }  
})

Use the key Property

Also, we can use the key property from the event object to the key that’s pressed as a string instead of a number.

For instance, we can write:

document.onkeydown = (e) => {  
  e = e || window.event;  
  if (e.key === 'ArrowUp') {  
    console.log('up arrow pressed')  
  } else if (e.key === 'ArrowDown') {  
    console.log('down arrow pressed')  
  } else if (e.key === 'ArrowLeft') {  
    console.log('left arrow pressed')  
  } else if (e.key === 'ArrowRight') {  
    console.log('right arrow pressed')  
  }  
}

We compare the key property value against the string names for the keys.

Also, we can use addEventListener method to add the key down listener by writing:

document.addEventListener('keydown', (e) => {  
  e = e || window.event;  
  if (e.key === 'ArrowUp') {  
    console.log('up arrow pressed')  
  } else if (e.key === 'ArrowDown') {  
    console.log('down arrow pressed')  
  } else if (e.key === 'ArrowLeft') {  
    console.log('left arrow pressed')  
  } else if (e.key === 'ArrowRight') {  
    console.log('right arrow pressed')  
  }  
})

Conclusion

We can detect arrow key presses by listening to the keydown event.

And in the event listener, we can either check the key or keydown properties of the event object to see which key is pressed.

Categories
JavaScript Answers

How to Remove the Last Item from a JavaScript Array?

Removing a last item from the JavaScript array is something that we’ve to do sometimes with our code.

In this article, we’ll look at how to remove the last item from a JavaScript array.

Array.prototype.splice

We can use the JavaScript array’s splice method to remove the last item from the array.

For instance, we can write:

const array = [1, 2, 3]
array.splice(-1, 1)
console.log(array)

We call splice with -1 to remove the last item from the array.

And 1 specifies that remove one item.

Then array is [1, 2] .

Array.prototype.pop

We can call the pop method to remove the last item from the array.

It returns the item that’s been removed.

To use it, we can write:

const array = [1, 2, 3]
const popped = array.pop()
console.log(popped, array)

We call pop on array to remove the last item from array .

And we assigned the removed item to popped .

So popped is 3.

And array is [1, 2] .

Array.prototype.slice

Another array method we can use to remove the last item from an array is the slice method.

It returns an array with the start and end index.

For instance, we can write:

const array = [1, 2, 3]
const newArr = array.slice(0, -1);
console.log(newArr)

We call slice with the start and end index to return an array from the start index to the end index.

The item at the end index isn’t included, but the one in the start is included.

The number -1 means the index of the last item in the array.

Therefore, we get:

[1, 2]

as the value of newArr .

Array.prototype.filter

We can use the array filter method to return an array with items that meet the given condition.

Therefore, we can check if the item is in the last index of the array.

For instance, we can write:

const array = [1, 2, 3]
const newArr = array.filter((element, index) => index < array.length - 1);
console.log(newArr)

We pass in a callback to the filter method that returns index < array.length — 1 to return all the items with index less than array.length — 1 .

Therefore, we’ll get the same result for newArr as the previous example.

Conclusion

We can use JavaScript array methods to remove the last item from an array.

Categories
JavaScript Answers

How to Get Distinct Values From an Array of Objects in JavaScript?

Sometimes we may want to get distinct values from an array of objects in our JavaScript code.

In this article, we’ll look at how to get distinct values from an array of objects in JavaScript.

Extracting Values with Array Methods

One way to get distinct values from an array of objects in JavaScript is to use native array methods.

For instance, we can write:

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = array.map(item => item.age)
  .filter((value, index, self) => self.indexOf(value) === index)
console.log(uniques)

to call the map and filter to return unique values of the age property from all the items in the array.

We call map to return an array with all the age values.

Then we use filter to return an array with distinct values of the age value array returned from map .

The callback we pass into filter has the value , index and self parameters.

value has the value being iterated through.

index has the index of the value .

And self is the array itself.

We can check if it’s the first instance of a given value with self.indexOf(value) === index .

indexOf returns the index of the first instance of value in the array.

So we can use that return an array that only has the first instance of a given element.

Therefore uniques is [17, 35] .

We can replace the filter call by putting the age value array in a set and then spreading that back into an array:

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = [...new Set(array.map(item => item.age))]
console.log(uniques)

And uniques has the same value as the previous example.

The spreading can be replaced with the Array.from method:

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = Array.from(new Set(array.map(item => item.age)))
console.log(uniques)

since Array.from works with any iterable objects, including sets, to convert them into an array.

Lodash

Lodash has the uniq method to return unique values from an array of objects.

So we can use it by writing;

const array = [{
    "name": "jane",
    "age": 17
  },
  {
    "name": "joe",
    "age": 17
  },
  {
    "name": "bob",
    "age": 35
  }
];
const uniques = _.uniq(_.map(array, 'age'));
console.log(uniques)

We call map to return an array of age values from array .

And then we call uniq on the returned array to get the unique values from that returned array.

So we get the same result for uniques as the other examples.

Conclusion

We can use native JavaScript array methods or Lodash to extract distinct values from a property from an array of objects.