Working with arrays in JavaScript objects

I have an object with arrays nested inside, as shown in the example below:

{1: Array(4), 2: Array(4), 3: Array(4)}
1: (4) ["11111", "2020-04-02", "14:07", 1]
2: (4) ["22222", "2020-04-02", "14:07", 2]
3: (4) ["3333333", "2020-04-02", "14:07", 3]
(from console log)

In my code, there is an option to add and delete arrays. If I delete the second array for example, it will become like this:

{1: Array(4), 3: Array(4)}
1: (4) ["11111", "2020-04-02", "14:07", 1]
3: (4) ["3333333", "2020-04-02", "14:07", 3]
(from console log)

How can I make the third object become number 2? I want the object to be managed from lowest to highest numbers. Thank you.

Answer №1

By converting your object into an array-like structure, you unlock the ability to utilize array methods on it.

An object that is considered array-like must contain a `length` property and keys that are positive integers. The value of `length` should be one more than the highest index present in the object. For example, if your object has keys `1, 2, 3`, then `length: 4` is needed. Despite there being only three elements, `length` essentially represents the "next available index."

Upon transforming your object, you can apply Array#splice by utilizing Function#call. Many array methods operate generically to accommodate any array-like data structure:

const obj = {
  1: ["foo"],
  2: ["bar"],
  3: ["baz"],
  length: 4
}

//delete starting from index 2 and remove 1 item
Array.prototype.splice.call(obj, 2, 1)

console.log(obj);

Observe how the indexes shift after deletion and the `length` automatically adjusts accordingly.

If unsure about the current `length`, it can be easily determined:

const obj = {
  1: ["foo"],
  2: ["bar"],
  3: ["baz"]
}


const keys = Object
  .keys(obj)   //get all keys
  .map(Number) //convert to numbers
  .filter(key => Number.isInteger(key) && key >= 0); //leave only positive integers

//find the highest
const highestKey = keys.reduce((a, b) =>  Math.max(a, b), -1);

//set the length to the next possible index
obj.length = highestKey + 1;

//delete starting from index 2 and remove 1 item
Array.prototype.splice.call(obj, 2, 1)

console.log(obj);

Answer №2

Deleting the second array from the object above results in only that key being removed, without affecting other keys. Object keys serve as identifiers to access the corresponding values' locations.

If you prefer all other keys to reset according to order, consider using arrays of arrays instead of objects with arrays as values.

An array consists of ordered items with numeral indices, while an object contains unordered items with any valid string or number indices.

In cases where using an object is necessary, here's a manual solution:

To remove the index i, adjust the subsequent indices (numerically greater than i) by decrementing their key value by 1.

// Indexing starts from 1 up to n.
const deleteElement = (delete_index, obj) => {
    const keyCount = Object.keys(obj).length;

    // Shift elements with keys > delete_index to previous index
    for(let i=delete_index; i<=keyCount; i++) {
        obj[i] = obj[i+1];
    }
    // Remove the last element
    delete obj[keyCount];
}


Answer №3

To remove elements from an array, you can utilize the splice method by specifying the index and number of items to remove. For example: arr.splice(2, 1)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I apply a class to the pre and code elements in Redactor?

I've been struggling for days to figure out how to add a class to the formatting option element within Redactor. By default, the "Code" formatting option wraps content in either <pre></pre> or <code></code> HTML elements. Howe ...

Tips for reversing the order of elements in a 2D Array

public void pieceDrop(){ int turns = 0; while(turns < 8){ System.out.println("Which column do you want to drop a piece into?: "); Scanner boardScanner = new Scanner(System.in); int inputColumn = boardScanner.nextInt(); ...

Filter out specific fields from an object when populating in MongoDB using the aggregate method

Is there a way to use the populate() function in MongoDB to exclude specific fields like email and address, and only retrieve the name? For example: const results = await Seller.aggregate(aggregatePipeline).exec(); const sellers = await Seller.populate(re ...

Unable to retrieve hours from MongoDB date array

Whenever I fetch data from my NodeJS+MongoDB webservice, I am able to retrieve the date format successfully. However, I am facing an issue when trying to extract hours from it. Here is how the date looks in MongoDB: https://i.stack.imgur.com/qxWGL.png I ...

IndexOutOfRangeException : 6

public boolean checkHorizontal(Populate populateObj, int[][][] array, int row, int col, int dep) { array = new int[6][6][6]; populateObj.pop(array); int count1 = 0; for(dep=0;dep<6;dep++) { ...

What are some ways to reinvigorate your determination?

With the use of ui-router, a state is created with a resolve function: .state('tab.social', { url: '/social/', views: { 'menuContent': { templateUrl: 'templates/social/tab-social.html', ...

What is the best way to find a specific string within an array in a MongoDB document and extract that array value during a search operation?

After creating and inserting simple json documents with arrays into mongo, the search for documents in the collection with array1 values beginning with 'field1' was initiated. MongoDB shell version: 2.4.6 use test > db.sandbox.insert({ "arra ...

Replicate the functionality of a LinkedList using a basic float array

I am faced with the task of displaying the trails left by an object moving around on a SurfaceView. These trails are represented as a LinkedList of points, where each point is a pair of float coordinates on the SurfaceView. The use of a LinkedList is inspi ...

Integrate data from Firebase into a React-Table component

I am currently working on a table component that fetches data from Firebase to populate three fields: Name Date Comment For each entry, I want to add a new row. The pivot has been successfully added. However, when trying to populate the table, I am encou ...

Can jQuery effortlessly glide downward, come to a stop, continue downward, and then move upwards?

My webpage features a large table created and populated automatically every minute using ajax. The code structure is as follows: $(document).ready(function(){ setInterval(function(){ $.ajax({ //code to call backend, get the data, ...

The results generated by the Google Maps API are consistently consistent

const request = require('request'); var geocodeAddress = (location) => { var encodedLocation = encodeURIComponent(location); request({ url: `http://www.mapquestapi.com/geocoding/v1/address?key=APIKey&location=${encodedLocation}` ...

Show only the objects in a MongoDB collection that have a matching status in another collection

I have two different collections - one called competition and the other called product. The competition collection contains the objectID of the product, while the product collection contains the competition_status. My goal is to only display the competiti ...

What is the best way to isolate particular components of an argument and store them in separate variables?

Currently, I am facing a challenge in extracting the name and id of an emoji from a discord argument using discord.js. The input provided to me is <:hack_wump:670702611627769876>, and my goal is to retrieve var id = '670702611627769876' alo ...

Manipulating the "placeholder" attribute with Knockout.js and JSON data

Is it possible to use the placeholder attribute with data-bind? I am encountering an error message ([object object]). Can someone help me figure out how to properly utilize it? html: input id="comments" class="form-control" data-bind="attr: { placeholde ...

Two-way binding with Angular2's NgModel can encounter issues

After executing a GET XMLHttpRequest against a service, I received the following JSON payload as a response : {_id: "5aa1358d32eba9e34dd9f280", source: "Avengers", target: "Iron Man", enemies: "Actor"} Within my src/app directory, I have defined the obje ...

Loop through an array of objects that each contain two sub-objects using ng

I'm looking to organize each data-record in an object that contains two other objects structured like this: data Object { abbData={...}, invoiceData={...}} abbData Object { service="24", conn_fee="0", month_fee="249", more...} invoiceData ...

A single Modal, Ajax, and data that is continuously refreshed

I'm currently facing a challenge in my project as I try to implement Ajax functionality. Although I'm relatively new to using it, I believe I have a basic understanding of its workings. My website involves collecting form data, posting it to a d ...

No change in the element's text content when clicking

I'm working on creating a timer that counts down from either 15 or 30 seconds. However, I'm having trouble changing the text value when the 15 button is clicked. Can someone help me figure out what's wrong? Thank you in advance HTML <h ...

How can I efficiently load AJAX JSON data into HTML elements using jQuery with minimal code?

I have successfully implemented a script that loads an AJAX file using $.getJSON and inserts the data into 2 html tags. Now, I want to expand the JSON file and update 30 different tags with various data. Each tag Id corresponds to the key in the JSON strin ...

Show a notification when the values of variables 'enter' are not the

I have a website featuring 2 text boxes, a button, and a paragraph. What I would like to do is have users input a number into textbox1, another number into textbox2, and then click the "calculate" button. Upon doing so, a statement should appear indicating ...