adding a new object to a list in JavaScript using the last key value

Need help with appending a new object list within a nested last key value in JavaScript. Here is my initial input:

var list = [12,13,14,15]

Desired output:

list = [{first : 12, sec : 13},{first:13, sec:14},{first:14, sec:15}]

Answer №1

To create objects by pairing each element with the next one, iterate through all elements except the last using a traditional for loop.

let data = [12, 13, 14, 15]
let result = [];
for (let i = 0; i < data.length - 1; i++)
  results.push({ first: data[i], second: data[i + 1] })

console.log(result);

Answer №2

If you want to transform the elements in a list and create a new list with the updated data, the map function is perfect for the job:

var numbers = [5,6,7,8];
const modifiedList = numbers.map(num => ({original: num, incremented: num + 1})).slice(0, -1);
console.log(modifiedList);

Answer №3

To combine and process data, you can utilize the .reduce method.

const numbers = [5, 10, 15, 20];
const result = numbers.reduce((accumulator, currentValue, index, array) => {
  if(array.length > index + 1) 
    accumulator.push({first: currentValue, second: array[index+1]})
  return accumulator;
}, [])

console.log(result)

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

Disabling the button using props will prevent its onClick event from triggering

For a quick solution, visit the react code sandbox and test the buttons by clicking them a few times. The Buggy button fails to reach the end of the slideshow. I am developing a horizontally scrollable slideshow. https://i.sstatic.net/51viM.gif The slid ...

Retrieve the file by utilizing the HTML obtained from the AJAX request

Currently, I am attempting to accomplish the task of downloading a file on the same page utilizing HTML generated from an AJAX call. The AJAX call is structured as follows: $.ajax({ url: './x ...

Updating and deleting Firebase data from an HTML table: A guide

I am struggling to make the onClick function work in order to update and delete already retrieved data from an HTML table view. Despite trying different approaches, I can't seem to get it right. var rootRef = firebase.database().ref().child("prod ...

function embedded in velocity.js chain

How can I effectively execute this code? I keep encountering various errors. After the sequence is completed, I want to incorporate an additional function. I am utilizing jQuery in conjunction with velocity.js $(".close").click(function(){ var my ...

Having trouble getting autocomplete to work with JQuery UI?

Currently facing issues in implementing the Amazon and Wikipedia Autocomplete API. It seems that a different autocomplete service needs to be used based on the search parameter. Unfortunately, neither of the services work when adding "?search=5" for Wikipe ...

Using Node.js to seamlessly read and upload files with Dropbox API

I am utilizing the Dropbox API to retrieve a file from the node.js file system and then transfer it into a designated Dropbox folder. The transfer process is successful, but the file ends up being empty, with a size of 0 bytes. var path = require("path") ...

Issue with NodeJS Express's reverse proxy due to an invalid TLS certificate alternative name

I have configured a reverse proxy on my endpoint as shown below: var express = require('express'); var app = express(); var httpProxy = require('http-proxy'); var apiProxy = httpProxy.createProxyServer(); var serverOne = 'https://i ...

How to replace the xth occurrence with jQuery or JavaScript

Looking for a solution to update a specific character in a string like the following scenario: var str = "A A A A A"; The goal is to replace a particular 'A' with another value. For example, replacing the 3rd 'A' with some ...

concealing additional content within a DIV using ellipsis

Looking to conceal additional text within my DIV element with ellipsis (...) at the end Currently using: <div style="width:200px; height:2em; line-height:2em; overflow:hidden;" id="box"> this is text this is text this is text this is text </div ...

What is the process for configuring the Sequelize Postgres model type to inet in a database?

I have been utilizing the sequelize ORM to manage my postgress database. Within my postgress database, we have been using the inet data type to store IPv4 and IPv6 values. While creating models in sequelize, I encountered the issue of not finding the ine ...

How can we redirect to the current page in JavaScript while passing an additional variable?

How can I capture the current URL and add "&p=1" to it before redirecting? Looking for a solution! ...

Angular - Collaborative HTML format function

In my project, I have a function that sets the CSS class of an element dynamically. This function is used in different components where dynamic CSS needs to be applied. However, every time I make a change to the function, I have to update it in each compo ...

Top tips for resolving Swiper Js initial loading issues in a Carousel!

After implementing swiper js from , I encountered an issue. The initial loading displays only a single carousel item before the rest start appearing, creating a glitchy effect. To clarify, when the website is loaded, only the first item is visible in the ...

Deciphering HTML with AngularJS

We are currently working with AngularJS version 1.5.6 and facing an issue with HTML characters not being displayed correctly in our text. Despite trying various solutions, we have been unsuccessful in resolving this issue. We have explored numerous discuss ...

Javascript Parameter

Each time I enter scroll(0,10,200,10); into my code, it seems to output the strings "xxpos" or "yypos" instead of the actual values. I attempted to remove the apostrophes around them, but unfortunately, that did not resolve the issue. scroll = function( ...

Guide to displaying database results in an HTML dropdown menu by utilizing AJAX technology

Greetings! As a newcomer to the realms of PHP and AJAX, I am currently on a quest to showcase the outcomes of a query within an HTML dropdown using AJAX. Let's delve into my PHP code: $pro1 = mysqli_query("select email from groups"); I made an attemp ...

Exploring the world of JMeter: capturing sessions with JavaScript and jQuery

I need to capture a user session in order to conduct a performance test. I have been using the JMeter HTTP(S) Test Script Recorder, but unfortunately it is not recognizing javascript and jquery. The error message I'm receiving is: JQuery is not def ...

Check input validations in Vue.js when a field loses focus

So I've created a table with multiple tr elements generated using a v-for loop The code snippet looks like this: <tr v-for="(item, index) in documentItems" :key="item.id" class="border-b border-l border-r border-black text ...

How can I remove the popover parents when clicking the confirm button using jQuery?

I am having trouble sending an AJAX request and removing the parent of a popover after the request is successful. I can't seem to access the parent of the popover in order to remove it, which is causing me some frustration. // Code for deleting w ...

javascript The image loading function only executes once

When working with my code, I encounter an issue related to loading and appending images. Initially, I load an image using the following code: var img = new Image(); img.src= 'image.png'; Afterwards, I append this image to a div like so: $(&apo ...