What is the best way to extract key-value pairs from an array of objects?

When using $http, I received the following JSON response:

{
    "fruits": [
        {
            "name": "apple",
            "prices": [
                {
                    "2015": 2
                },
                {
                    "2014": 3
                },
                {
                    "2013": 5
                }
            ]
        },
        {
            "name": "banana",
            "prices": [
                {
                    "2015": 1
                },
                {
                    "2014": 3
                },
                {
                    "2013": 4
                }
            ]
        }
    ]
}

In Javascript, I am attempting to create a mapping function to obtain two specific sets of data:

$scope.new_data = [
    {
        name: 'apple',
        data: [5,3,2]
    },
    {
        name: 'banana',
        data: [4,3,1]
    }
]

and

$scope.years = ['2013','2014','2015']

I have considered the following approach, but I'm unsure how to separate the keys and values:

$scope.new_data = $scope.fruits.map(function(fruit){
    return {
        name: fruit.name,
        data: fruit.prices
    };
});

$scope.years = $scope.fruits.map(function(fruit){
    return [
        fruit.prices.reverse();
    ];
});

Answer №1

You have the ability to streamline this process using a single .map function

var organizedData = data.fruits.map(function(fruit) {
    return {
        name: fruit.name,
        data: fruit.prices.map(function(price) {
            return price[Object.keys(price)[0]];
        }).reverse()
    }
});

var yearsList = [];
var allYearsCombined = data.fruits.map(function(fruit) {
    //Gather all years into a 2D array
    return fruit.prices.map(function(price) {
        return Object.keys(price)[0];
    });
}).reduce(function(previous, current) {
    //Merge 2D array into a flat array
    return previous.concat(current)
}, []);

//Eliminate any duplicate years
allYearsCombined.forEach(function(year) {
    if (yearsList.indexOf(year) === -1) {
        yearsList.push(year);
    }
});

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

The search results from the autocomplete feature of the Spotify API appear to be missing

Exploring the Spotify API - I am attempting to implement an autocompletion feature using jQuery for a field that suggests artists as users type. Here is what I have so far: HTML: <input type="text" class="text-box" placeholder="Enter Artist" id="artis ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

Unlock the Power of JavaScript: Understanding Multidimensional Input Field Array Indexing

Here is a sample HTML form with multidimensional input fields. <tr> <td><input name="diameter[0][top]" type="text" id="diameter_top0" size="5" class="diameter" /></td> <td><input name="diameter[0][bottom]" type="te ...

What could be causing the issue with npm install packages not functioning properly?

Currently, I am in the process of setting up and deploying a particular git repository locally: https://github.com/maxie112/gatsby-ecommerce-theme I am strictly adhering to the instructions provided for Mac OS. Here are the encountered error logs; maxden ...

Bundle Thirdparty Dependencies with Webpack

I am looking to package a webpack bundle that includes all common third-party vendors such as Angular 1.4, jQuery, and other libraries. Currently, the following modules have been developed: Module A Vendor Module Vendor Module: Create a simple module ...

What is the best way to save data in MONGO DB with Java programming language?

Creating a blog post feature in my web application has been an interesting journey. Initially, I relied on mysql as the database to store the posts entered in the text area of the blog as an object in JavaScript. The process involved sending this object to ...

Update JavaScript variable value when there is a change in the onchange

Greetings, thank you for taking the time to read this. I am currently working with an input that includes a datepicker calendar. This calendar has variables called minDays and MaxDays which allow users to select a specific number of days. In my HTML form, ...

The .val() function in jQuery does not function properly for autofilled username and password fields on browsers like Chrome and Firefox

In order to enable a login button only when the length is not 0 and both the username and password fields are not empty, a particular code is executed. This functionality works perfectly fine under normal circumstances. However, it seems that when I save m ...

Saving instances of a Class in an array

Take a look at the following code snippet: dispenserType type[4]; dispenserType appleJuice(); type[0] = appleJuice; dispenserType orangeJuice(); type[1] = orangeJuice; dispenserType mangoLassi(); type[2] = mangoLassi; dispenserType fruitPunch(); type[3] = ...

Utilizing Javascript to maintain an ongoing sum within a <span> tag

I'm working on a code snippet to create a running total feature. Essentially, every time a user clicks a button to add the subtotal to the total, I want it to keep accumulating in the running total. Currently, the setup involves a dropdown menu with t ...

glitch discovered in the validation process of phone numbers

I've been working on a phone number validation code where I need to verify if the input is numeric. Below is the code snippet that I have been using: var phoneres; function checkphone(num) { var filter = /^[0-9]{3}\-[0-9]{7}$/; if (filt ...

Navigating with AngularJS and Express

Check out my code on Plunker where I have implemented these routes. 'use strict'; var app = angular.module('app', ['ngResource', 'ui.router','ngAnimate', 'ui.bootstrap']) .controller(' ...

Tips for fixing a type error in javascript/cypress

While learning cypress and javascript, I encountered this type error: TypeError: _testElements.default.selectionRow is not a function I have thoroughly reviewed the documentation for cypress but cannot seem to find any errors in my code. I'm hoping ...

Neglecting to send a socket signal while assigning a variable to a socket message

In my client-side script, I am using the following snippet: socket.on('bla', function(data) { if (data == ID) { console.log('I don't understand what's happening here.'); } }) socket.on(ID, function(data) { ...

What level of security is involved in sending an ajax request to a Codeigniter controller?

I am looking to securely pass the response of an ajax request to my codeigniter application. The current approach I have is as follows: Javascript var dataString = { 'id' : id }; var submit = $.ajax({ url:$('#hiddenurl').v ...

Angualr's functionality with Http request is malfunctioning

I am attempting to utilize Angular and API services to populate data from my database. Here is my code snippet: $http.get("/api/trips") .then(function (response) { angular.copy(response.data, vm.trips); }, function (error) { vm.er ...

for each item, assign a unique ink color

Hello there! Currently, I am working on a straightforward online shopping MVC application. Within this application, there is a table containing three categories: Laptops, Mobiles, and Consoles. I have created a partial view that fetches these categories fr ...

In the realm of C++ programming, arrays, functions, and counters

After successfully writing and testing my code, I encountered a challenge in figuring out how to count the number of attempts made by the user and identify any invalid account numbers entered. The task is to implement this functionality within the main f ...

The scenario of two users simultaneously gaining control access in socket.io creating a race condition

There is a need to ensure that only one user at a time is notified for an available room. I am implementing a solution to prevent multiple users from being notified simultaneously for the same room. socket.on('Check', function (room) { io.in(r ...

The UI-date timepicker in Angular JS does not allow the timepicker box to be closed by clicking on the input

Trying out the uidatetimepicker simple demo In this demo, I have customized it by eliminating the clock icon and adding an ng-click action to the input field. I want the input to not only open the time form but also close it upon a certain action: First ...