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

How can we use JavaScript to retrieve an element with custom styling?

I've encountered a strange issue with my script where it seems to stack up borders and display a 2px border instead of the intended 1px border when switching elements on click. Here is the link code I am using: <li ><a href="plumbing.php"&g ...

Is it possible to prevent a webpage from being refreshed?

I need help with an HTML page that puts the worker on pause time which will be subtracted from his/her day job. The issue is that when he/she refreshes the page, the timer starts from the beginning automatically. I want it to continue without resetting. Is ...

Experiencing a Typescript error when trying to access a property within a nested object

My current challenge involves typing an object, which seems to be error-free until I try to access a nested property and encounter the dreaded red squiggle. After some research, I came across suggestions like this: type FlagValue = string | boolean | numb ...

Issue encountered while implementing async functionality in AngularFireObject

I'm encountering difficulties with the async feature in AngularFireObject. Is there a solution available? Snippet from HomePage.ts: import { AngularFireObject } from 'angularfire2/database'; export class HomePage { profileData: Angu ...

The specified file ngx-extended-pdf-viewer/assets/pdf.js cannot be found

I have integrated the ngx-extended-pdf-viewer package in my Angular application using npm to enable the display of PDF content. According to the setup instructions, I have added the following configuration in my angular.json file: "assets": [ ...

The Google timezone API is displaying an inaccurate daylight saving offset

London now has an additional +1 hour of daylight saving time. I made a request to the Google timezone API for the London timezone, but unfortunately, it is not displaying the correct time. https://maps.googleapis.com/maps/api/timezone/json?location=51.507 ...

What is the best way to send an object to Vue Component?

How can I properly call a Vue Component with a data object? The todo-item tag works as expected, but the todo-item2 tag does not produce any output. I was expecting the same result. Here is the HTML code: <div id="app"> <todo-item v-bind:te ...

Tips for preventing a React component from scrolling beyond the top of the page

I am looking to achieve a specific behavior with one of my react components when a user scrolls down a page. I want the component to reach the top of the page and stay there without moving any further up. Here is an Imgur link to the 'intranet' ...

In Vue using Typescript, how would I go about defining a local data property that utilizes a prop as its initial value?

When passing a prop to a child component in Vue, the documentation states: The parent component updates will refresh all props in the child component with the latest value. Avoid mutating a prop inside a child component as Vue will warn you in the consol ...

Transforming JSON data into comma-delimited values (with thousands separators) using Angular 5 and ES6 syntax

Is there a more elegant method to convert a JSON response into comma-separated numbers for displaying currency purposes? Here is the code I have currently: let data = { "business":{ "trasactionTableData":[ { ...

The renderValue property is malfunctioning in the Material-UI native Select component

Whenever I utilize the native prop in the MUI Select component, the renderValue prop fails to function properly. Additionally, if I attempt to assign a custom value to the value prop, it does not display. Take a look at the code snippet below: const [selec ...

Analyzing JSON data and creating a tailor-made array

My Dilemma { "rowId": "1", "product_name": [ "Item A", "Item B", "Item C", "Item D", "Item E" ], "product_tag": [ "123456", "234567", "345678", "456789", "5678 ...

Error message: AngularJS Jasmine spyOn: number has no functionality

I am encountering difficulties while attempting to execute a test that utilizes a mockup for a service call (retrieving location data from a web SQL database). Below is the controller code: .controller('LocationDetailCtrl', function ($scope, $s ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

transform nested object into a flat object using JavaScript

here is the given JSON format: - { "_id": "5c1c4b2defb4ab11f801f30d", "name": "Ray15", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddced69e9aefc8c2cec6c381ccc0c2">[email protected]</a>" ...

Tips for preventing users from entering special characters into input fields

How can I prevent users from entering the # character into an HTML input field? I attempted to use the pattern attribute, but it does not seem to be effective. I included this pattern in my input element: pattern="[^-#]+" I expected that this would disa ...

TypeScript: defining a custom type with a collection of properties following a consistent pattern

I am looking for a way to create a type that can accommodate any number of properties following a predefined pattern, like so: type Values = { id: number; id1?: number; id2?: number; id3?: number; // ... somethingElse: string; anotherOne: num ...

Having trouble importing XML data from an external file with jQuery

Attempting to import external XML with the code below is proving unsuccessful $( document ).load( "data.xml", function( response, status, xhr ) { console.log( xhr.status + " " + xhr.statusText ); }); Both data.xml and js files are in the ...

Tips for modifying string in key-value pairs on the client side (example using Paypal checkout demo)

Looking to integrate an online payment system into my small online business, I have decided on using PayPal. Their solution is user-friendly and can be found here: https://developer.paypal.com/demo/checkout/#/pattern/client However, I am facing an issue w ...

Select the implied type from a resolved Promise type in Typescript

I am working with a function called getStaticProps in Next.js that returns a Promise, resolving to an Object with the following structure: type StaticProps<P> = { props: P; revalidate?: number | boolean; } To generically "unwrap" the type o ...