Is the value being used as the key for the array of objects?

Here is an array of objects:

{
    'data': [{
            value: 1000,
            year: 1990
        },
        {
            value: 1001,
            year: 1990
        },
        {
            value: 1002,
            year: 1990
        },
        {
            value: 1003,
            year: 1991
        },
        {
            value: 1004,
            year: 1991
        }
    ]
}

The objective is to convert the above array into an object that looks like this:

{
    '1990': [{
            value: 1000,
            year: 1990
        },
        {
            value: 1001,
            year: 1990
        },
        {
            value: 1002,
            year: 1990
        }],

    '1991':[{
            value: 1003,
            year: 1991
        },
        {
            value: 1004,
            year: 1991
        }
    ]
}

Is there a way to achieve this in Javascript or Angular 4?

Answer №1

To efficiently go through each item in the array, utilize the Array#reduce function. This function allows you to check if the accumulate object contains a property with a specific key. If it doesn't, add the key to the object and assign an array to it before pushing the item into that array. If the key already exists, simply push the item.

const data = [{
            value: 1000,
            year: 1990
        },
        {
            value: 1001,
            year: 1990
        },
        {
            value: 1002,
            year: 1990
        },
        {
            value: 1003,
            year: 1991
        },
        {
            value: 1004,
            year: 1991
        }
    ];
    
const mapped = data.reduce((acc, item) => {
   
   if(!acc.hasOwnProperty(item.year)) {
      acc[item.year] = [];
   }
   
   acc[item.year].push(item);
   
   return acc;
    
}, {});

console.log(mapped);

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

Workaround for syncing MobX observables when toggling a select/deselect all checkbox

In my application, there is a checkbox list with a 'Select All' checkbox at the top. The list is populated by an observable array of strings. When the user clicks on 'Select All', it should check all checkboxes; subsequent clicks should ...

What is a more efficient approach to managing the response from an asynchronous call other than using setState?

Utilizing javascript async await, I have been making service calls to the server in componentDidMount or componentDidUpdate. However, when I need to pass the response data as props to other components, I find myself updating the component's state with ...

Information released by JavaScript through AJAX and JSON

Hello everyone, I've been trying to merge two different Ajax codes together and it's been quite a challenge. As a novice, I know I may sound ridiculous but I really need some help... My goal is to convert an array into JSON and display the data ...

Transitioning from a fixed position to absolute in CSS3

Sticky Logo Element In my project, I implemented a logo element that is positioned absolutely within the document. As the user scrolls, the logo sticks to the top of the window with a fixed position (you can view an example here: https://jsfiddle.net/swzb ...

Is the statement true in JavaScript if either true or true or false?

I have implemented this code snippet to prevent my page from being iframed: window.onload = function(){ try { if (window.parent && window.parent.location.hostname !== "app.herokuapp.com"){ throw new Error(); } catch (e){ //do something ...

What is the proper way to write a function that verifies the presence of a key in an object and then retrieves the associated value?

After holding out for a while hoping to stumble upon the solution, I've decided to give it a shot here on SO since I haven't found it yet. import { PDFViewer, MSViewer } from './viewerclasses' //attempting to incorporate a union of key ...

Getting Values from .Properties File in JavaScript/HTML pages that are Executing in a Node.js Server

I have a configuration file named "site.properties" with the following content: #Properties file #Database Connection Info db.host.name = localhost db.user.name = username db.password = password db.database.schema = db1 #Server Connection Info ...

Javascript loop malfunctioning

Within my project using kinetic.js for HTML5 canvas, I have an array filled with code that needs to be executed. To accomplish this, I utilize a for loop to iterate through the array and employ eval() to run the code. This array is named tiles, which cont ...

Is there a way to dynamically change an icon based on certain conditions using typescript?

I am struggling with displaying icons in my TypeScript code using Material Icons. I need to dynamically change the icon based on a condition, for example if the power is false I want to display 'power_off', but if it's true then I want to di ...

Error thrown when attempting to access properties of null values (Uncaught TypeError: Cannot read properties of undefined (reading 'map'))

import React, { useState, useEffect } from "react"; import { TaskLists } from "./TaskLists"; import { Daycard } from "./daycard"; import { getTasks, deleteTask } from "../api/task.api"; export function TaskManager() { const [tasks, setTasks] = useState( ...

Changing an array into an object in JavaScript without rearranging the keys

I have a collection { 1: {id: 1, first: 1, last: 5} 2: {id: 2, first: 6, last: 10} 3: {id: 3, first: 11, last: 15} } My goal is to reverse the order of items without rearranging the keys so that it looks like this: { 1: {id: 3, first: 11, last: 15} 2: { ...

Function is not triggered in React component

When the LoginPage calls AuthForm, the structure is as follows: function mapDispatchToProps(dispatch: Redux.Dispatch<any>) { return { signUpWithEmail: function(email: string, password: string) { // bla bla }, }; } handleForm ...

Exploring AngularJS: the power of directives and the art of dependency

According to Angular documentation, the recommended way to add a dependency is by following these steps: Source //inject directives and services. var app = angular.module('fileUpload', ['ngFileUpload']); app.controller('MyCtrl&ap ...

Check if any element from the first array exists in any nested array of the second array and return a Boolean

Having two distinct types of arrays, firstArrayObject = [{name: "sample", number: 23}, {name: "sample2", number: 25}]. The second object takes the form of secondObject = {someAttribute: bla, numbers: [23, 26, 27, 28} My goal is to det ...

The drop-down menu fails to appear when I move my cursor over it

#menu { overflow: hidden; background: #202020; } #menu ul { margin: 0px 0px 0px 0px; padding: 0px 0px; list-style: none; line-height: normal; text-align: center; } #menu li { display: inline-block; } #menu a { display: block; position: relative; padding ...

Tips for Keeping a Responsive Image at the Forefront of a Text-Image Layout as You Scroll

I'm currently in the process of creating a website where text appears on the left side with an accompanying image on the right. The challenge I'm encountering is ensuring that as users scroll, the image adjusts dynamically based on the associated ...

How can a reusable ng-pattern be written in AngularJS?

I need to validate multiple fields in my application as valid French phone numbers. How can I efficiently reuse the regular expression for multiple input fields without repetitive copy and paste? Also, how can I localize the regex for easier management? ...

Can you suggest a solution for fixing this error in Angular Js?

I recently started learning Angular JS and encountered some issues while trying to implement routing. Click here for the error message <!DOCTYPE html> Main <a href="#!london">City 1</a> <a href="#!paris">City 2& ...

Using data fetched from PHP in HTML via jQuery post: A step-by-step guide

I have created a function in jQuery that uses $.post to send data to a PHP file. The query in the PHP file is working fine and returning the data back successfully. JavaScript code: function send_agenda_data(cidade_data){ var data = {'cidade_dat ...

Manipulate JQuery plug-in properties within an AJAX request using MVC

Currently, I am utilizing a Jquery time picker sourced from Within the view, there exists this time picker control. $("#startTime").timePicker({ startTime: "09.00", endTime: new Date(0, 0, 0, 19, 0, 0), show24Hours: false, ...