Adding JSON data before the second to last element of an array:

I am looking to create a function that can consistently add JSON Items to an array just before the last item.

const array = [ 
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
  { USA: { Score: '15', PlayedMatched: '06' } },
  // Insert Items Here
  { 'Index Value': 12 }      
]

const insert = (arr, index, newItem) => [
    ...arr.slice(0, index),
    newItem,
    ...arr.slice(index)
]


var insertItems= [{ 'Japan': { Score: "54", PlayedMatched: "56" } },{ 'Russia': { Score: "99", PlayedMatched: "178" } }];

// I have tried like this: array.slice(-1) to insert item one step before always

const result = insert(array,array.slice(-1),insertItems)

console.log(result);

OutPut:


[ [ { Japan: [Object] }, { Japan: [Object] } ],     //Not at Here
  { India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' } },
  { USA: { Score: '15', PlayedMatched: '06' } },
  { 'Index Value': 12 } ]

Expected Output:

[ 
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
  { USA: { Score: '15', PlayedMatched: '06' } },
  [ { Japan: [Object] }, { Japan: [Object] } ],      //At here
  { 'Index Value': 12 }
]

What is the correct way to achieve this? Also, how can I remove the square brackets [] in my output results? :)

Like This:

 [ 
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
   { USA: { Score: '15', PlayedMatched: '06' } },
  { 'Japan': { Score: "54", PlayedMatched: "56" } },
  { 'Russia': { Score: "99", PlayedMatched: "178" } },
  { 'Index Value': 12 }      
]

Answer №1

To successfully insert a new item into an array, simply specify the desired index number as the index parameter in the insert function. In this scenario, you want to insert the new items in the second-to-last position, so you should pass array.length - 1.

const array = [ 
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
  { USA: { Score: '15', PlayedMatched: '06' } },
  { 'Index Value': 12 }      
]

const insert = (arr, index, newItem) => [
    ...arr.slice(0, index),
    ...newItem,
    ...arr.slice(index)
]


var insertItems= [{ 'Japan': { Score: "54", PlayedMatched: "56" } },{ 'Russia': { Score: "99", PlayedMatched: "178" } }];



const result = insert(array,array.length - 1,insertItems)

console.log(result);

Answer №2

To utilize the splice method, follow this format:

const list = [ 
  {India: { Points: '12', MatchesPlayed: '21' } },
  { China: { Points: '52', MatchesPlayed: '51' }},
  { USA: { Points: '15', MatchesPlayed: '06' } },
  { 'Index Value': 12 }      
]

var newItem= [{ 'Japan': { Points: "54", MatchesPlayed: "56" } },{ 'Russia': { Points: "99", MatchesPlayed: "178" } }];

list.splice(list.length - 1, 0, ...newItem)

console.log(list);

It is important to note that splice will alter the original array provided and not produce a modified duplicate.

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

Understanding XML parsing problems

I've decided to keep the live xml/atom-feed URL private, as it's hosted on LiveJournal. However, I'm a bit confused about how this all works: let XML_URL = "https://users.livejournal.com/<username>/data/atom"; $(function(){ ...

Is there a restriction on the number of strings allowed in minimist?

Here is the output received from the code provided below. Question input and i are both true as intended, but why aren't project and p? They are defined in exactly the same way as input and i. $ bin/test --input -p { _: [], update: fa ...

Unexpected interactions between Socket.io and React using hooks

Currently, I am delving into the world of Socket.io with React utilizing Hooks. My goal is to create a timer that starts upon pressing the start button, and then every second, send the current time in the state to the server using socket.io. The server co ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

What is the best way to determine the moving average of an Object value within an array?

In my dataset, I have an array called 'scores' that contains 4 objects. export const scores = [ { day: '1', Barcelona: 1, Real: 3, Valencia: 0}, { day: '2', Barcelona: 4, Real: 6, Valencia: 3}, { day: '3', Bar ...

Fetching json data from the request in Node.js

I'm currently working on a project that involves using the request module to send an HTTP GET request to a specific URL in order to receive a JSON response. However, I've run into an issue where my function is not properly returning the body of ...

Videos embedded using the React HTML video tag are not automatically playing on mobile devices

I have implemented a jsx variable to insert a video into my html. Despite following the advice to include muted defaultMuted, and playsinline (which I have already done), the videos autoplay on safari, chrome, and firefox on my computer but not on mobile ...

Embracing the Unknown: Exploring Wildcard Values

I have a code snippet below that has a wildcard * in it. I'm looking for suggestions on how to make the * accept any number. Any thoughts on this? $('body').on('click', '.custom_295_*-row', function(){ var href = "htt ...

After submitting my form, the Bootstrap Modal does not hide as intended by my Ajax

I am facing an issue with my webpage that displays 6 Bootstrap Cards in 3 columns. Each card contains an image, name, description, and a footer button. When a user clicks on the button, a Bootstrap Modal opens with specific data fetched from a SQL row by I ...

Tips to prevent the webpage from scrolling to the top when clicking on an anchor with an ID

I have developed a CSS/HTML carousel that consists of 4 slides. The goal is to display the selected slide when clicking on the bottom button (a href). However, I am facing an issue where every time I click on a link, the selected slide appears as intended ...

Selecting default values from the Vuex store in Vue-Multiselect

Picture a Vuejs-Application equipped with Vuex. I am aiming to incorporate a mulitselect-dropdown. Here's a basic example inside the Vue-component: <template> <div> <multiselect v-model="values" :options="options"> ...

Incrementing the index in Javascript when an event occurs

I am currently working on a project that involves incrementing an index of an array based on certain events, such as a left mouse click over a designated area. The code snippet provided below initializes all values to zero and briefly changes the relevan ...

Encountering a PropertyTypeError while attempting to process a payment via Stripe in conjunction with use-shopping-cart on Next.js

Upon reaching the checkout page, I encounter the message: Invalid value with type "undefined" was received for stripe. Valid type for stripe is "string". This issue seems to be related to the redirectToCheckout function. Can someone assist me? The cart-s ...

Sending multiple unique forms with the same structure using JavaScript and Ajax on a single PHP page

In my PHP page, there are 12 individual forms with unique form IDs, checkboxes, and dropdowns. Take a look at this image: https://i.stack.imgur.com/pODzk.png Each form has an Update Zone that fetches Name, Enable status, Time, Dim information, and sends ...

Difficulty encountered with Mongoose/MongoDb FindOneAndUpdate functionality

My goal is to update a specific location only if it has a status of 0 or 2, but not if the status is 1. There is only one instance of this location in my database. Property.findOneAndUpdate({ status: 0, location: req.body.update.location }, req.body.updat ...

Determining whether a PFUser is being created or updated with the AfterSave function

Struggling to differentiate between whether a PFUser is being updated or saved for the first time? I tried implementing a solution from parse.com here, but it's not working as expected. No matter what, I always end up with a false value, be it an init ...

Trouble getting Fontawesome icons to accept color props when using react functional components with tailwindcss

Issue I'm Facing I'm currently working on a project that involves using icons extensively. Instead of manually adding a Fontawesome icon in every script, I have created a functional component that handles the rendering of icons based on given pr ...

Downloading Files from Mongodb Using GridFS

I am working on an application that enables users to upload and download various files. Currently, I am facing a challenge where I am able to retrieve the file from my MongoDB database and download it locally on my machine, but I am encountering difficulti ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

Send information from a web page's elements to PHP with the help of AJAX

My goal is to integrate AJAX, HTML, and PHP to create a seamless user experience. I am currently facing difficulty in passing variables to the PHP form. The method I've employed seems a bit complex, especially since this is my first attempt at using A ...