Tips on transforming an object containing arrays into a single array

I'm facing a challenge with converting an object that contains an array into a simpler array. The backend I'm working with returns a list of dogs along with their prices in a format that's proving difficult to manipulate. I've attempted various methods to convert the object into a more manageable array, including attempting to reduce it.

For example, let's say I want to transform the following object:

const data = {
    dogs: [{
            "id": "dog1",
            "priceRange": [
                "low",
                "high"
            ],
            "vaccinated": true,
        },
        {
            "id": "dog2",
            "priceRange": [
                "low",
                "high"
            ],
            "vaccinated": false,
        }
    ],
    "cost": [{
            "id": "low",
            "cost": 200,
        },
        {
            "id": "mid",
            "cost": 400,
        },
        {
            "id": "high",
            "cost": 600,
        }
    ]
};

into this simplified array:

const newArray = [{
        "id": "dog1",
        "priceRange": [{
                "id": "low",
                "cost": 200,
            },
            {
                "id": "high",
                "cost": 600,
            }
        ],
        "vaccinated": true,
    },
    {
        "id": "dog2",
        "priceRange": [{
                "id": "low",
                "cost": 200,
            },
            {
                "id": "high",
                "cost": 600,
            }
        ],
        "vaccinated": false,
    }
]

I'm still exploring different approaches and solutions for this issue.

Answer №1

To get the accurate cost value, you should first loop through your array of dogs in a.dogs. During each iteration, iterate over the priceRange array as well to match its corresponding value inside the a.cost array and return that specific value instead of the generic strings "low" or "high".

a.dogs.map(dog => ({
    ...dog,
  priceRange: dog.priceRange.map(priceRange => a.cost.find(cost => cost.id === priceRange))
}))

Answer №2

  • Utilizing the Array#reduce method, loop through the elements in the array a.cost while updating a Map where the key corresponds to the object's id and the value is the object itself.
  • Using Array#map, iterate over the elements in the array a.dogs and assign the priceRange values based on the Map using another iteration with Array#map.

const a = {
  "dogs": [ { "id": "dog1", "priceRange": [  "low", "high" ], "vaccinated": true }, { "id": "dog2", "priceRange": [ "low", "high" ], "vaccinated": false } ],
  "cost": [ { "id": "low", "cost": 200 }, { "id": "mid", "cost": 400 }, { "id": "high", "cost": 600 } ]
};

const costMap = a.cost.reduce((map, cost) => 
  map.set(cost.id, cost)
, new Map);

const reducedArray = a.dogs.map(dog => ({
  ...dog, 
  priceRange: dog.priceRange.map(range => {
    const { id, cost } = costMap.get(range) || {};
    return { id, cost};
  })
}));

console.log(reducedArray);

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

What is the best way to retrieve a nested object array using a Signal in Angular/Typescript?

In my Angular/Typescript code, I am encountering an issue with filtering a nested object array based on the object property where value === 'event'. Despite my efforts, the code is returning the parent object array CalendarModel[] instead of the ...

I desire for my advertisement to be showcased whenever I click on a href link

Hello there, I have implemented the following script to showcase my advertisement: <a href="<?php the_permalink() ?>" onclick="func()" title="<?php the_title(); ?>" rel="bookmark"><?php the_title(); ?></a> I am utilizing the ...

Tips for modifying the HTML generated on the server side before it is rendered on the client side in Quasar

Just starting out with Vue.js and looking to implement Vue I18n. However, I'm facing an issue setting the locale on Vue I18n and also setting the HTML lang attribute to the same locale. The challenge is that I can't access the document object in ...

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

Three.js Ellipse Curve Rotation

Purpose My goal is to create an EllipseCurve () where a camera will move. The Approach I Took to Achieve the Goal Below is the code snippet for creating the ellipse: var curve = new THREE.EllipseCurve( 0, 0, 1, 1, 0, 2 * Math.PI, false, ...

Angular HTML is throwing an error related to object arrays

Is there a way to display only specific fields of an array? <div class="form-check" *ngFor="let periodo of filterPeriodos()"> <div>{{periodo.periodos | json}}</div> <input class="form-check-input mr- ...

The connection between the type of request and the corresponding response in an Ajax function

When using the following: xhr.setRequestHeader("Content-Type", "application/json"); Am I obligated to only receive a response in json format, or is it possible to receive an html response instead? If there is flexibility in receiving different formats, h ...

javascript method to retrieve specific value from row column upon button click

Take a look at my HTML code below: <div class="container"> <table class="table table-bordered"> <thead> <td>Name</td> <td>Address</td> <td>Ci ...

I am having issues with the accuracy of my JavaScript number validation function

function CheckIfNumeric() { var quantity = jQuery("#txtShippedQuantity").val(); quantity = quantity.toString(); for (i = 0; i < quantity.length; i++) { var character = quantity.charAt(i); if (isNaN(character)) { ...

Data sent through AJAX messaging is not being acknowledged

I recently made an AJAX request and set it up like this: $.ajax({ data : { id : 25 }, dataType : 'json', contentType : 'application/json; charset=utf-8', type : 'POST', // the rest of the ...

Can components in Vue.js share functions?

Within my application, there exists a plethora of utility functions that handle various tasks such as parsing strings and displaying toasts. My main inquiry is regarding how to access these functions within other .vue files without the need for redundant ...

CSS trick for masking line borders with parent corner radius

I'm currently utilizing next js for my web application, and I have encountered a specific requirement that needs addressing. You can find the visual representation of this requirement in the following image: https://i.sstatic.net/zGVrl.png The progr ...

The Dropdownlist jQuery is having trouble retrieving the database value

Within my database, there is a column labeled Sequence that contains integer values. For the edit function in my application, I need to display this selected number within a jQuery dropdown list. When making an AJAX call, I provide the ProductId parameter ...

Prevent JavaScript from sending a POST request to a specific URL

Currently facing Cross Site Scripting (XSS) vulnerabilities in a web application, I am curious if there are security measures equivalent to Content-Security-Policy: frame-ancestors and X-Frame-Options for JavaScript. My objective is to restrict the abilit ...

Is there a way to dynamically fetch and run JavaScript code from the server without resorting to the use of the

In my current project, I am developing a unique PHP framework that empowers PHP developers to effortlessly craft ExtJS interfaces containing forms, grids, tabpanels, and menus exclusively through PHP classes. To illustrate, creating a TabPanel in this fra ...

Tips for choosing the default first option in a select box or dropdown menu

I'm having trouble displaying a select box using a directive. The default option is not showing up. This is what I have: <div> <select ng-init="userselected = vm.data[0]" ng-model="userselected" ng-options="optio ...

Using a PHP for loop in conjunction with data from a database and an API yields a singular calculated result

I am attempting to iterate through a PHP script to calculate the Total Holding of an individual's Portfolio. However, my code is only displaying one calculated field from the database instead of all available. Here is the structure of my database: i ...

Tips for efficiently storing multiple sets of border coordinates to generate a polyline

I'm struggling with finding a solution for storing multiple borders for a location. I have a table for locations that includes id, latitude, longitude, total space, and borders. In the borders field, I need to save multiple latitude and longitude pair ...

Is it better to use scale.set() or simply increase the size of the model in Three.js?

When it comes to scaling 3D models in Three.js (or any other 3D renderers), what is considered the best practice? Recently, I encountered a situation where I loaded a model only to realize that its size was too small. In order to adjust the size, I used m ...

Intermittent issue with div background switching feature on Firefox

There's a div where background images are changed using a script. I've simplified everything here: Sometimes, in Firefox, an error occurs about 10% of the time that looks like this: https://i.sstatic.net/JvSfx.png Everything seems to work fine i ...