How to modify a specific property of an array object in JavaScript

I have an array of objects that looks like this:

[
  {
    number: 1,
    name: "A"
  },
  {
    number: 2,
    name: "e",
  },
  {
    number: 3,
    name: "EE",
  }
]

I am looking for a way to insert an object into the array at a specific position and then adjust the numbers of the rest of the objects so they are in sequential order. Similarly, I need to be able to remove an object and shift the numbers back accordingly.

For example, if I insert at position 1 with name: "F", the array would become:

[
  {
    number: 1,
    name: "A"
  },
  {
    number: 2,
    name: "F"
  },
  {
    number: 3,
    name: "e",
  },
  {
    number: 4,
    name: "EE",
  }
]

I have come up with some solutions, but I'm not entirely satisfied with them. Here are a few thoughts:

  1. I tried using this.arr.splice(1, 0, newObj) to insert, followed by looping through the array to increment the numbers where necessary. It works, but it's not elegant.
  2. Another approach was to splice the array, create a new array excluding the inserted element, and then use splice again to replace part of the original array with the new one.

Here is a snippet of my code that achieves the desired outcome, but I'm open to suggestions on how to simplify or improve it:

const newObj = {
  number: obj.number + 1,
  name: 'S',
}
this.arr.splice(obj.number, 0, newObj)
if (this.arr.length > obj.number) {
  const remaining = this.arr.slice(obj.number + 1).map( (t) => ({...t, ...{number: t.number + 1}}))
  this.arr.splice(newObj.number, remaining.length, ...remaining)
}

Answer №1

To achieve the desired outcome, one can utilize the splice(index, deleteCount, item) method and leverage the index in a map function to assign numbers to each object sequentially. This allows for adding and deleting elements while maintaining the correct sequence of numbers.

let arr = [
  {
    number: 1,
    name: "A"
  },
  {
    number: 2,
    name: "e",
  },
  {
    number: 3,
    name: "EE",
  }
]

let newObj = {
name: "F",
  }
arr.splice(1,0, newObj)//To add
  //  console.log(arr)

//arr.splice(2,1) //To delete
//console.log(arr);

console.log(arr.map((v,i) => {
  v.number = i;
  return v
}));

For more information on Array.splice, visit this link - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Answer №2

To manipulate arrays, you can leverage spread syntax along with slice.

  • The operation determines whether a value is added or deleted.
  • If the operation is set to del, we slice the array from index 0 up to the specified index and then from index+1 to the end.
  • Otherwise, we slice from start to index, add the desired value, and then append the remaining part back (from index to end).
  • Finally, use map to update the number property accordingly.

let arr = [{ number: 1,name: "A"},{number: 2,name: "e",  }, {number: 3,name: "EE",}]

let handleArray = (array, operation, index, value) => {
  if(operation === 'del') {
    return [...array.slice(0, index), ...array.slice(index+1,)].map((value,index)=> (value.number = index+1, value))
  } else {
    return [...array.slice(0,index), value, ...array.slice(index,)].map((value,index)=> (value.number = index+1,value))
  }
}

console.log(handleArray(arr,'add',0,{a:1}))
console.log(handleArray(arr,'del',0))

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

The Best Approach for Angular Google Maps Integration

I'm diving into Angular for the first time while working on a project that requires advanced mapping functionality like clustering, routing, road routing, paths, directions, polygons, events, drawing on maps, info windows, markers, etc. After some re ...

Pytest is not able to locate any elements on the webpage, yet the same elements can be easily found using the console

When using CSS or XPath in the console (F12), I am able to locate the element on the page. $$("span.menu-item[data-vars-category-name='Most Popular']") However, when trying to find the same elements with Selenium (pytest) using: driver.find_el ...

"Counting Down with PHP and jQuery : A Dynamic

I recently received a tutorial on how to combine PHP date function with jQuery. I am looking to modify the script so that when a specific time is reached, it redirects to another page. I attempted to make the changes myself but encountered some issues. Y ...

Three JS does not support dynamic color changing functionality

In my ThreeJS project, I have created a 3D wall and am attempting to change its color dynamically on a click event. However, the code doesn't seem to be working as expected. Can you help me identify the error in the following code snippet? var materi ...

What is the process for accessing a table in indexedDB using Dexie.js immediately after it has been opened?

I am faced with the challenge of needing to verify if a specific table already exists in IndexedDB right after it has been opened. However, I am unsure how to access the DexieDB object inside the 'then' statement. this.db = new Dexie("DBNAME"); ...

The initial setting of [opened]="true" causes an issue with the Angular Material date range picker

Recently, we completed the upgrade of our app from Angular 14 to 15.2.9, which includes Angular Material. The migration process went smoothly, and now our app is compiling and running without any errors. However, we encountered an issue with the mat-date-r ...

I'm having trouble getting my object to display using ng-repeat in Angular. Can anyone help me understand what I'm missing?

My goal was to add an object to an array upon clicking an event, which I successfully achieved. However, the objects are not displaying in the ng-repeat as ordered. Can you help me figure out what's missing? angular.module('app', []); an ...

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

Triggering a client-side dialog in Electron-Angular upon receiving an IPC event

I am experiencing a strange issue with my back-end notification system and client-side Angular Material dialog component. There are times when the dialog does not fully instantiate, even though the constructor of the component is invoked. The component&apo ...

Creating a full-screen loading animation that appears when a button is clicked is a great way to enhance user experience. This animation can flow seamlessly from right to left before disappearing, providing a visually engaging transition for users as they

Despite anticipating more negative responses than positive ones, I believe that even one correct answer outweighs it all! So, I'm trying to figure out how to create a loading animation that covers the entire screen whenever a button on the navigation ...

Utilizing React Hooks efficiently with JSDoc annotations and destructuring arrays

Seeking guidance on how to properly JSDoc a React Typescript component that uses hooks, specifically when working with declared destructured arrays. Despite my efforts, I have not been able to find a solution that allows JSDoc to work seamlessly with destr ...

Returning a value with an `any` type without proper validation.eslint@typescript-eslint/no-unsafe-return

I am currently working on a project using Vue and TypeScript, and I am encountering an issue with returning a function while attempting to validate my form. Below are the errors I am facing: Element implicitly has an 'any' type because expression ...

How come the sentence array is displaying 38 elements even though it's supposed to only accommodate 30?

#include <iostream> #include <vector> #include <string> #include <cstring> using namespace std; int main() { //initialize a char array and a vector char sentence[30] = {}; vector<string> words{"The", "on ...

What is the inner workings of stream.Transform in Node.js?

Recently, I stumbled upon a code snippet on a blog showcasing the usage of the stream Transform class to modify data streams and display the altered output. However, there are certain aspects of this code that leave me puzzled. var stream = require(&apos ...

Tips for updating a React state while using the history API

In an effort to simplify and stay focused on the problem, I recently wrote a brief piece of code. Within this code, there is a component containing a Dialog that plays a role in a commercial process. This Dialog allows users to input information such as no ...

Having trouble with getting v-cloak to function properly when dealing with asynchronous requests

I wanted to explore using the v-cloak directive to showcase a loading spinner while certain data properties in vue js are being loaded asynchronously for me to integrate into a table component. After successfully applying and styling my v-cloak styles on ...

Display a div every 3 seconds with the help of jQuery

I am seeking a solution to display the second div (box2) every 3 seconds. Can anyone help me achieve this using jQuery? <div id="box1" style="background-color:#0000FF"> <h3>This is a heading in a div element</h3> <p>This ...

Using JavaScript in conjunction with IPFS to verify the 404 status from localhost:8080 and identify if the local IPFS node is active within a browser user script

As a newcomer to IPFS and JavaScript, I have successfully created a simple IPFS userscript that redirects addresses containing *://*/ipfs/* or *://*/ipns/* to http://localhost:8080/<IPFS_HASH>. However, there is an issue when the local IPFS node is ...

Incorrect .offset().top calculation detected

Within a webpage, I have multiple sections. Positioned between the first and second section is a navbar menu. As the user scrolls down and the navbar reaches the top of the page, a function is triggered to fix it in place at the top. While this functionali ...

Is it possible in C# to read data from a text file and populate multiple arrays or classes simultaneously?

As a beginner in c# and coding, I am seeking some assistance. I came across a way to save data to a 2d array from a text file in a previous discussion. However, I now have a task where I need to split the file into multiple arrays. Here is my attempt so fa ...