Combine key value pairs in a JSON object into a list using Javascript

In my dataset, I have JSON files containing information spanning from the year 2008 to 2020, along with additional data keys like location and name:

{"2008": 50, "2009": 60, "2010": 70, "2011": 80, etc...}

My goal is to organize these years into a new key and include it in the existing array:

{metric:
    [{"year": 2008, "perc": 50},
     {"year": 2009, "perc": 60},
     {"year": 2010, "perc": 70},
     {"year": 2011, "perc": 80}],
 "2008": 50, 
 "2009": 60,
 "2010": 70, 
 "2011": 80,
 etc...
}

To accomplish this, I believe I need to establish a range between 2008 and 2020. If any keys fall within this range, they should be added to the metrics group and included in the array.

Answer №1

If you have an object instead of an array, you can iterate through it using a for-in loop or a for-of loop on Object.entries. Once you have accessed the values, you can convert the year to a number and check if it falls within your specified range. If it does, you can add it to the metric array:

const data = {"2008": 50, "2009": 60, "2010": 70, "2011": 80, "2001": 20, "2002:": 30};
// Loop through the object
for (const [year, perc] of Object.entries(data)) {
    // Convert the year to a number
    const yearValue = +year; // Refer to note below
    if (yearValue >= 2008 && yearValue <= 2020) {
        // Year is in range, access the `metric` array
        const metric = data.metric ?? (data.metric = []);
        // Add the values
        metric.push({year, perc});
    }
}

console.log(data);

(I included some out-of-range years to demonstrate how the range works.)

Utilizing unary + for conversion to a number is just one approach; there are several options available, which I discuss in detail in my answer here.

Answer №2

You should iterate through the object and create a fresh one

const transformObject = obj => {
    // Define initial object
    let output = {
        metric: []
    }

    // Loop through the object
    for (const key in obj) {

        // Check if the property exists in the object
        if (Object.hasOwnProperty.call(obj, key)) {

            // Check if the key falls within a certain range and add it to the 'metric' array if not
            if (!(/20(0[8-9]|1[0-9]|20)/gm).test(key)) output.metric.push({
                'year': key,
                'perc': obj[key]
            });
                
            // Add the value to the output object if the key falls between 2008 and 2020
            else output[key] = obj[key]
        }
    }

    // Return the new object
    return output;
}

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

AJAX request post parameters not recognized in ColdFusion form scope

I am currently developing a ColdFusion 8 training application that involves creating AJAX requests without using any libraries like jQuery. This is to support a basic CRUD application where data is retrieved and processed through various layers of the syst ...

Show side by side using javascript

My dilemma lies in having a set of cards that are meant to be displayed inline, but I have to initially hide them using "display: none". When a specific button is clicked, I aim to reveal these cards; however, upon doing so, each card seems to occupy its o ...

What is the best way to retrieve a single value from this JSON array?

Here is the data retrieved from MPI ELAN, specifically related to movie files used in the program: '[{"MEDIA_URL": "file:///Volumes/MINI RUGGED/MULTIMET2015/JOINT/29-60-S1.avi", "MIME_TYPE": "video/*", "TIME_ORIGIN": "176040"}, {"MEDIA_URL": "file:/ ...

Inform the PHP backend that the browser has been closed by the frontend Angular application

Currently, I am working on an Angular project that is interacting with a backend project created using PHP and ZF3. I am trying to figure out the most efficient method of informing the backend project when the user closes the browser window. Initially, I ...

Converting a NumPy Array containing characters into a string

My numpy array contains characters, but when I save it to a file, it appears like this: ['K' 'R' 'K' 'P' 'T' 'T' 'K' 'T' 'K' 'R' 'G' 'L&apos ...

Challenges with rendering in Vue.js when setting up a simplistic Trello-style system using Mongoose and MongoDB

I'm currently developing a basic functionality kanban board. Currently, I have 4 models set up: User Model var userSchema = new Schema({ name: { type: String, required: true } }) module.exports = mongoose.model('User', userSc ...

Eliminating the page loading 'hiccup' during jQuery processing

Visitors to my website are experiencing a brief glitch lasting half a second on each page before any jQuery code kicks in. This script is responsible for rearranging elements on the page, causing them to shift all at once, resulting in a clunky user experi ...

Starting service upon startup in Angularjs

I am looking to retrieve configuration data from the server and store it in the global scope within my AngularJS application. My app operates in multiple modes such as development and production, with different external services being used depending on the ...

Ensure the accuracy and secure storage of information in Laravel using axios

I am using React\NextJS for the frontend and Laravel for the backend, I am currently storing data with Axios post method as shown below, const storeExpense = async (expenseData) => { const response = await axios.post('/api/expenses/stor ...

Leverage Express.js route variables for universal access

I'm currently working on integrating the Spotify API with my express.js server and facing a challenge in accessing an Authorization code from a URL parameter. I've managed to retrieve this value using let code = req.query.code within the callback ...

Looking for assistance with organizing a JSON array

My web service returns an array with the following data: {"update":true,"msg":"Logged in Bro","role":"admin"} Now, I am looking to integrate this data into my Android application beyond just logging in. To achieve this, I need a way to format the data eit ...

The process of refreshing a TableView using JSON data

I'm facing a challenge with updating data on my website from JSON. I have a TableView that retrieves data from a JSON URL. When I click the button, the information from JSON is displayed in the tableviewCell, but I want this information to update auto ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

Visualizing network graphs using JavaScript

I am in search of a JavaScript network visualization graph (not a chart) that can handle JSON input effectively. I have tried using the JIT infovis toolkit, RGraph, and space tree to display multiple levels in the graph. However, I have encountered issue ...

Transform the HTML pattern regex into JavaScript format

I am struggling to get this particular function to work: function ausPhoneValidate(str){if (/^(?:\+?(61))? ?(?:\((?=.*\)))?(0?[2-57-8])\)? ?(\d\d(?=[^\\d{3}])|([^\\d\\d[- ]?\\d[- ]) ...

The map functionality is failing to render on the three.js object

function generate_geometry(scene) { var mesh; var material; var texture; var geometry; geometry = new THREE.BufferGeometry(); geometry.attributes = { position: { itemSize: 3, array: ...

Discovering the indices within an array that satisfy a specific condition using Python and the numpy library

I'm looking to simplify this expression using a more concise pythonic approach, possibly utilizing numpy. The numpy.argwhere() function did not give the desired results when checking if a value falls within a specified range. myList = [4.2, 6.0, 10.2] ...

I am facing a challenge with AngularJS where I am unable to navigate between pages using the

I'm having issues with my route file app.js. Whenever I click on any link or button, it redirects me to books.html. What could be the mistake I'm making? var myApp = angular.module('myApp', ['ngRoute']); myApp.config([&apo ...

What is the best method for obtaining a spring controller's object using AJAX?

Here is the AJAX call I am working with: var url = "UsersGroupReader.html?selectedCompanyName=" + selectedCompanyName + "&test="+Math.random(); req.onreadystatechange = processAccessGroupRequest; req.open("GET", url, true); req.send(null); function ...

Choosing the Best Data Format for a 2D RPG: XML, YAML, or JSON

Deciding between XML, YAML, or JSON for a C++ 2D RPG is proving to be a challenge. Considerations: I require a solution that can easily store player data along with environment details like object coordinates, load times, dates, graphics settings, etc ...