What is the best way to retrieve the first items from an array of objects?

When I send an axios request like this:

async fetch() {
  await this.$axios.get(`my_api_url`)
    .then(response => {
       this.data = response.data;
     }).catch(() => { console.log('error') })
 },

The response contains the following data:

{
    "Apple": [
        {
            "id": 26,
            "name": "Apple",
            "date_in": "2020-07-01"
        },
        {
            "id": 23,
            "name": "Apple",
            "date_in": "2020-06-01"
        }
    ],
    "Cherry": [
        {
            "id": 24,
            "name": "Cherry",
            "date_in": "2020-06-01"
        }
    ],
    "Banana": [
        {
            "id": 25,
            "name": "Banana",
            "date_in": "2020-06-01"
        }
    ]
}

I would like to filter through this object and only keep the first entry of each category. Then, I want to display these selected objects in a new table.

Is there a way to accomplish this task?

Answer №1

def ExtractItems(data):
    result = []
    for element in data:
        result.append(element[1])
    return result

If my interpretation of your query is accurate

Answer №2

Is this what you're looking for?

const data = {"Apple":[{"id":26,"name":"Apple","date_in":"2020-07-01"},{"id":23,"name":"Apple","date_in":"2020-06-01"}],"Cherry":[{"id":24,"name":"Cherry","date_in":"2020-06-01"}],"Banana":[{"id":25,"name":"Banana","date_in":"2020-06-01"}]},

      resultArr = Object.values(data).map(([obj]) => obj)

console.log(resultArr)
.as-console-wrapper{min-height:100%;}

Alternatively, could it be like this instead?

const data = {"Apple":[{"id":26,"name":"Apple","date_in":"2020-07-01"},{"id":23,"name":"Apple","date_in":"2020-06-01"}],"Cherry":[{"id":24,"name":"Cherry","date_in":"2020-06-01"}],"Banana":[{"id":25,"name":"Banana","date_in":"2020-06-01"}]},

      resultObj = Object.entries(data).reduce((acc,[key,[obj]]) => 
        (acc[key] = obj, acc), {})


console.log(resultObj)
.as-console-wrapper{min-height:100%;}

Answer №3

If you follow the code snippet below:

const information = {
    "Grapefruit": [
        {
            "id": 26,
            "name": "Apple",
            "date_in": "2020-07-01"
        },
        {
            "id": 23,
            "name": "Apple",
            "date_in": "2020-06-01"
        }
    ],
    "Strawberry": [
        {
            "id": 24,
            "name": "Cherry",
            "date_in": "2020-06-01"
        }
    ],
    "Pineapple": [
        {
            "id": 25,
            "name": "Banana",
            "date_in": "2020-06-01"
        }
    ]
}

const resultValues = Object.keys(information).filter(entry => information[entry][0]).map(item => information[item][0]);
console.log(resultValues);

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

Exploring the functionalities of quill modules in conjunction with vue2-editor and webpack mix

I am encountering an issue while using vue2-editor and importing Quill modules, despite registering them as instructed. The error message states that window.Quill is undefined. Even after attempting to include window.Quill and Quill with webpack plugin mi ...

Encountering generator crashes when using Vue Cli remote presets

While attempting to develop a remote Vue CLI preset on GitHub, I encountered a syntax error that I cannot seem to resolve. You can find my preset repository here: https://github.com/christoph-schaeffer/vue-preset The command I entered is as follows: vue ...

Is there a way to rotate a div without utilizing the "transform" CSS property?

I am currently utilizing a plugin from the SVG library to render graphics within a div (). However, I am encountering an issue when attempting to rotate it using the "transform" property. The rotation is purely visual and does not alter the X and Y axes of ...

Sharing specific information with a particular component instance in React using .map

I have set up multiple instances of a child component within a parent component using the following code: render() { return ( {this.state.accounts.map(account => <EachAccount key={account.id} curAccountData={account} /> ...

Adding Vuetify to your Astro project is a breeze!

Struggling with integrating Vuetify 3 into Astro using Vue integration. Here's my current setup: import { defineConfig } from 'astro/config'; import vue from '@astrojs/vue'; import vuetify from 'vite-plugin-vuetify'; / ...

Invoking Javascript Functions using their names

Suppose I have the following element on my page... <span data-function="DoSomething">Click</span> ... and then add the following to my page header... $(document).ready(function() { $('[data-function]').each(function() { ...

Swapping out the initial occurrence of every word in the list with a hyperlink

I stumbled upon a fantastic script on a programming forum that almost fits my requirements perfectly. It essentially replaces specific words in a document with links to Wikipedia. However, I have run into an issue where I only want the first occurrence of ...

JavaScript - utilizing a confirmation dialog box within a function

My JavaScript code was working well because I received some fantastic solutions here yesterday. I am now wondering if I can enhance this JavaScript with another query. Currently, the query triggers an alert when the number is greater than 199, and it is fu ...

Engaging User Forms for Enhanced Interactivity

I'm in the process of developing an application that involves filling out multiple forms in a sequential chain. Do you have any suggestions for creating a more efficient wizard or form system, aside from using bootstrap modals like I currently am? C ...

The error message "email() is not a valid function when using the onclick attribute

Can anyone lend a hand? I feel like I must be overlooking something really obvious. I'm having trouble calling my function to execute my ajax call. Any assistance would be greatly appreciated. Thank you! Here is an excerpt of the HTML code: $(docu ...

Transforming Several Dropdowns using jQuery, JSON, and PHP

Hey there! I'm looking to update the state depending on the country and city based on the chosen state. <label>Country:</label><br/> <select onchange="getval(this)"> <option value="">Select Country</op ...

Assigning a value to an input field using jQuery

I'm facing an issue while trying to set the value for an input using jQuery. Essentially, when you click on a link, it redirects you to a different page with a form, and I am attempting to set the value of one of the inputs in that form. Unfortunately ...

Error encountered during decryption with AES encryption: 'ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH'

I am attempting to decrypt data retrieved from MongoDB using a key and initialization vector (IV) that were stored in an environment function. However, I keep encountering the following error: ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH app.get("/recieve", as ...

PHP and AJAX failed to retrieve post data

I encountered some puzzling issues when attempting to send post data to a php file using xmlhttp request: Below is the javascript code snippet: function getHeaterDailyConfig(){ var oReq = new XMLHttpRequest(); var d = new Date() now = [d.g ...

Guide for implementing tabs using router-view in Vue.js

I've been utilizing vuesax [ https://github.com/lusaxweb/vuesax ] for managing tabs. Within vs-tabs, I have multiple router-views. I am looking to display different Vue template files for each respective tab of the router-view. Below is the code snip ...

Using Node.js, Handlebars, and Express for template inheritance

As I embark on my Node.js learning journey, I am starting with creating simple applications to grasp the fundamentals. Recently, I wanted to implement a Django-like template structure in my projects but found myself stuck on how to achieve it. I have come ...

Calling a controller method from within a directive in AngularJS is not possible

I'm currently developing a hybrid Ionic1 app and I am facing an issue with calling a controller method from within a directive. In the directive, I can pass variables from the controller (like the variable apps), but I am unable to call the removeCred ...

What is the best way to incorporate AngularJS data into JavaScript for use in Google Chart?

How can I leverage my AngularJS scope data in a Google Chart or JavaScript? Below is my AngularJS file: angular.module('reports').controller('ReportInfoCtrl', ['$scope', 'reports', '$rootScope','$loca ...

How to use jQuery to remove a class from the last entered data in a form

Reminder: This is a jQuery coding challenge, and I am required to write the validation script without using any plugins or additional modules. I have created a basic form validation script. If a user inputs data that is empty, an appropriate error message ...

Optimal methodologies for AngularJS components in content management system-based applications

Seeking the optimal approach for creating Angular 1 components with a CMS-driven strategy. My goal is to develop various label templates in a component-driven, highly reusable manner, fueled by CMS content. My plan is to utilize JSON as a component tree ...