Remove Objects from Associative Array with JavaScript

02/09/2022

Contents

In this article, you will learn how to remove objects from associative array with JavaScript.

Associative array in JavaScript

In JavaScript, there is the associative array in addition to the normal array.

In the normal array, each element is stored corresponding to a number starting from 0 (index).

const fruits = ["apple","orange","banana"];

console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "orange"
console.log(fruits[2]); // "banana"

On the other hand, the associative array allows you to associate keys with values.

const signals = {red: "stop", green: "go ahead", yellow: "attention"}

console.log(signals[red]); // "stop"
console.log(signals.red); // "stop"

console.log(signals[green]); // "go ahead"
console.log(signals.green); // "go ahead"

console.log(signals[yellow]); // "attention"
console.log(signals.yellow); // "attention"

Remove objects from associative array

Use the delete property to remove an element in an associative array.
The delete property returns true if the element was successfully deleted, false otherwise.

The syntax is below.

delete array.key
// or
delete array[key]

Below is sample code that removes an element from an associative array.

const signals = {red: "stop", green: "go ahead", yellow: "attention"}

delete signals.red;
delete signals[yellow];

for (let key in signals){ 
 console.log(`${key} : ${signals[key]}`)
}
// green : go ahead