Flatten information from an object containing multiple objects within an array

In my current project using Vue, I am making an API call to retrieve data from my Laravel backend (nova). The returned data is structured in the following way.

The data consists of an array, which contains arrays of objects. Each array represents a record, with each object representing a field within that record.

It is possible for a record to contain unnecessary additional data.

const data = [
    [
        {
            attribute: 'id',
            value: 1,
            extra: "not needed data"
        },
        {
            attribute: 'title',
            value: 'The Title',
            extra: "not needed data"
        },
    ],
    [
        {
            attribute: 'id',
            value: 2
        },
        {
            attribute: 'title',
            value: 'The Other Title'
        },
    ],
]

I am looking for a way to efficiently flatten this structure using Javascript so that it transforms into:

const data = [
    {id: 1, title: 'The Title'},
    {id: 2, title: 'The Other Title'}
]

My Attempts So Far

I have experimented with combinations of map and filter functions, but unfortunately, the results fell short of the desired outcome.

Answer №1

To create an object using only the attribute and value, excluding all other properties, you can utilize a combination of map and reduce:

const data = [
    [
        {
            attribute: 'id',
            value: 1,
            extra: "not necessary information"
        },
        {
            attribute: 'title',
            value: 'The Title',
            extra: "not necessary information"
        },
    ],
    [
        {
            attribute: 'id',
            value: 2
        },
        {
            attribute: 'title',
            value: 'The Other Title'
        },
    ],
]

console.log(data.map(a => a.reduce((a, o) => (a[o.attribute] = o.value, a), {})))

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 issue of req.files being undefined in Express.js

I am aiming to upload files to s3 without depending on any middleware like multer. Below is the code snippet of my approach: <form role="form" action="/send" method="post"> <input type="file" name="photo" class="form-control"/> <button ...

Issue with Angular Script not functioning upon reopening the page

I recently completed my first website, which can be found at Despite my efforts, I've encountered an issue that has me stumped. When you navigate to the certificate page, you should be able to input your name onto the certificate. However, if you sw ...

Uh-oh: create-react-app installation has been canceled

As per the guidelines provided in Reactjs documentation: To start a new project, you must have Node version >= 8.10 and npm version >= 5.6 installed on your system. Use the following command to create a project: npx create-react-app my-app My envir ...

Tips for calculating the canvas-relative mouse position on a CSS 3D transformed canvas

Recently decided to challenge myself by experimenting with drawing on 3D transformed canvases. After some trial and error, I managed to get it partially working. const m4 = twgl.m4; [...document.querySelectorAll('canvas')].forEach((canvas) =& ...

Delete an element from an array once an AJAX response has been received

As a Vue.js beginner transitioning from jQuery, I find myself frustrated and struggling with basic concepts for a simple project. Specifically, I am attempting to delete an article only after receiving an ajax response, displaying a spinner while waiting. ...

Retrieve storage information when an internet connection is unavailable on React Native

One of my recent projects involves creating an application that retrieves data from a URL in the form of an array of objects and then displays this data using FlatList. Upon launching the application, the data is displayed correctly since it's retriev ...

Managing Events in Angular 2 and Creating Custom Event Handlers

Currently, I am in the process of developing a component library in Angular 2 for our app teams to utilize. One of the components I recently created is a modal, but I am encountering some accessibility challenges. Specifically, I want the modal to close wh ...

Amcharts displays individual balloons for each graph instead of a single balloon for all graphs

My goal is to have a single balloon for all stacked graphs. I modified my code according to this guide. Unfortunately, the data for messages is not being displayed. Did I make an error in my implementation? function createChart(chartDiv, title) { ret ...

What is the comparable javascript code for the <script src="something1.json"></script> tag?

Within my HTML code, I currently have the following line to read a JSON file: <script src="something1.json"></script> Inside this JSON file, there is a structure like so: var varName = { .... } This method of definition naturally sets up ...

Jest snapshot tests using react-test-renderer encounter null references in refs

Having an issue with manually initializing the Quill editor in componentDidMount and encountering Jest test failures. It seems that the ref value I am receiving is null in jsdom. There is a related issue here: https://github.com/facebook/react/issues/7371, ...

What is the best way to transform a JS const into TSX within a Next.js application?

Exploring the code in a captivating project on GitHub has been quite an adventure. The project, located at https://github.com/MaximeHeckel/linear-vaporwave-react-three-fiber, showcases a 3D next.js application that enables 3D rendering and animation of mes ...

Preventing the removal of a choice by disabling it in the selector

I have a unique selector that is designed like this: <select id="patientSelector"> <option disabled selected style='display: none;' id="select0"> New Patients to Come</option> <option id="select1"></opt ...

Having trouble displaying the collection data from firebase using React

I am having an issue retrieving a collection from firebase and then using a map function to loop through the documents and render some UI elements. The data is correctly logged in the console at line 20, however, the map function doesn't seem to be wo ...

How can I pass a JavaScript variable through the URL in a Rails 4 application to access it in the controller?

Struggling to pass the value of a JavaScript variable in the URL and then retrieve it in my Rails 4 app controller using param[:my_variable]. Despite trying various methods, none seem to work for me. I am unable to successfully pass my JavaScript variable ...

Discovering if an element is present with Cypress.io

Is there a straightforward way to determine if an element is present, and then proceed with specific steps based on its presence or absence? I attempted the following approach, but it did not yield the desired results: Cypress.Commands.add('deleteSo ...

Having trouble converting binary data to base64 using GridFS-stream

As I attempt to convert some binary data from uploaded images to base64 in order to display an image, the terminal is throwing back this error: TypeError: Cannot read property 'on' of undefined I find it puzzling, as when I post I also utilize ...

What is the best method for saving a chosen radio button into an array?

I am currently developing an online examination system where questions are retrieved from a database using PHP and displayed through AJAX. I am facing an issue where I am unable to capture the selected radio button value and store it in an array. Despite e ...

Adding Proxy-Authorization Header to an ajax request

It's surprising that there isn't much information available online about this issue I'm facing. When attempting to include a proxy authorization in the header of my ajax call, I encounter some difficulties. If I send it as shown below, no er ...

Unable to save a URL link in MySQL database using JSON and PHP

I am seeking some insightful advice regarding my college assignment. This time around, I have to create yearbooks using Phonegap and it's my first experience working with AJAX, JSON, and JQuery Mobile. Instead of uploading an image directly into the ...

Initial React render fails to retrieve API data

I've encountered an issue during development where the page loads before the API data is sent. I attempted to use asynchronous functions, but it didn't resolve the problem as expected. I suspect that my approach may be incorrect. Here's a sn ...