Transform the JSON response

Is there a way to transform the following data into A-Apple, B-Apple, A-Mango?

{
        "Apple": [
            "A",
            "B"
        ],                                         
        "Mango": [
            "A"
        ]
    }

Answer №1

Could you provide more details on your desired outcome rather than just asking for a solution? One approach is to utilize Object.entries to iterate through and extract [key, value] pairs before processing the data further.

Are you looking for the final result in the form of a string or an array?

Refer to the example snippet below for guidance.

const array = {"Apple": ["A","B"],"Mango": ["A"]};
let results = [];


//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
for (const [key, value] of Object.entries(array)) {
  // Extract values for each key and iterate over them
  var values = (value || "").toString().split(",");
  // Loop through values and customize output with key/value pair
  (values || []).forEach(val => {
      results.push(`${val}-${key}`);
  });
};

const asArr = results;
const asString = results.join(', ');

console.log(`As ${typeof asArr}: ` + asArr);
console.log(`As ${typeof asString}: ` + asString);

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 use of a MongoId object as an array is not allowed

I am struggling with displaying the values inside a 2D array using echo. It works perfectly fine with print_r: print_r($array); The output is as follows: Array ( [0] => MongoId Object ( [$id] => 57a789b7ce2350b40e000029 ) [1] => MongoId Object ...

Arranging an array in Angular 7 with various states and numbers

Looking to tackle this array sorting issue in Angular 7, the data is fetched from the API: "Products": [ { "ProductCode": "MC30180", "Description": "Description_1", "NationalCode": "N.C. 0965", "Pend ...

What are the best practices for utilizing databases with both Javascript and JSF frameworks?

I am currently following the recommendations provided by @BalusC, with additional guidance available here. (The reason I'm posting this here is because it's not related to my previous question). My goal is to retrieve data from my database and d ...

How can you retrieve the `categoryIds` key within an object that holds an array of mongodb's `ObjectId(s)` as its value?

In my Node.js code, I have the following: var getQuestionsByUserId = function (config) { var query = { _id: ObjectId(String(config.userId)) }; var projection = { categoryIds: true, _id: false }; var respondWithCategories = function (error, doc ...

Tips for transferring a Spring MVC controller variable to JavaScript

I am currently working on retrieving a variable for a JavaScript function from an object that is sent to the view by the controller. The object I am dealing with is called Bpmsn. https://i.sstatic.net/FxlAo.png Through the controller, I have injected th ...

The webpage is displaying an error stating that "<function> is not defined."

I recently duplicated a functional web page into a new file on my site. However, after adding a new function and removing some HTML code, the JavaScript function no longer runs when clicking one of the two buttons. Instead, I receive the error message "Beg ...

Angular 2 Update RC5: Router Provider Not Found

I'm encountering an issue with the latest Angular 2 RC5 router (router version is RC1). Below is the error log from the dev console: EXCEPTION: Error in /templates/app.component.html:2:0 ORIGINAL EXCEPTION: No provider for Router! This is how my ap ...

How can one ensure the preservation of array values in React?

I'm struggling to mount a dynamic 'select' component in React due to an issue I encountered. Currently, I am using a 'for' loop to make API calls, but each iteration causes me to lose the previous values stored in the state. Is t ...

Embracing Error Handling with ES6 Promises

I am seeking clarification on how errors travel through a series of then continuations to a catch continuation. Consider the following code: Promise.reject(new Error("some error")) .then(v => v + 5) .then(v => v + 15) .catch(er ...

Using JSON in JavaScript to handle the click event of ASP.NET buttons

Here is the code that works well for me. I need to execute two different server-side functions, and they can't run at the same time as I have separated them. Default.aspx/AddCart btnUpdate Click Event The issue I'm facing is that the alert box ...

What is the method for dynamically updating and showcasing a JSON file upon the click of a button?

I'm currently developing an add-on that will display a panel with checkboxes and a save button when a toolbar button is clicked. The goal is to allow users to select checkboxes, then save the selected data in a JSON file that can be accessed and updat ...

Discover how to shallow test for the presence of a wrapped component using Jest and Enzyme

Currently, I am in the process of testing a component that dynamically renders another wrapped component based on certain conditions. My testing tools include enzyme and jest, with the root component being rendered using the shallow() method. The main chal ...

What steps can you take to address Git conflicts within the yarn.lock file?

When numerous branches in a Git project make changes to dependencies and use Yarn, conflicts may arise in the yarn.lock file. Instead of deleting and recreating the yarn.lock file, which could lead to unintended package upgrades, what is the most efficie ...

Combining multiple records into a single string in BigQuery is a common operation

I am dealing with a table that contains query jobs, each with a repeated record column called referenced_tables. This record consists of 3 columns and multiple rows. My goal is to convert the entire record into a single string using '.' as a sepa ...

Merge numerous datasets according to the student identification number

Having a challenging time trying to merge two MongoDB collections based on a student's ID. One collection holds personal information of students while the other contains their logs. The complication arises from the fact that the data is stored in arra ...

"React issue: Troubleshooting problems with using .map method on arrays of

I am struggling with the following code: const displayData = (data) => { console.log(data);// this displays an array of objects if (!data.length) return null; return data.map((movie, index)=>{ <div key={index} className=&qu ...

Failing to hide a div on hover: Hoverintent's shortcomings

When I hover over the div with the unique identifier id="navbar", it doesn't seem to trigger any actions. I have included the following script in my document head: <script type="text/javascript" src="https://ajax.googleapi ...

Adding multiple clones of Node to an array of objects using a POST request

I am working with a mongodb model that has the following structure: ingredients: [ quantity: Number, measurement: String, name: String ] Currently, these ingredients are being inputted through a single form where users can add new ingredients by cl ...

Analyzing the differences between an std::array and a conventional array in C++

I'm attempting to compare elements from: std::vector<std::array<uint8_t, 6> > _targets = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x11 } { 0x00, 0x00, 0x00, 0x00, 0x00, 0x22 } }; with a standard array: uint8_t _traditional[6] = { 0x00, 0 ...

What is the best way to transfer variables defined in PHP to JavaScript?

Can the variables previously defined in JavaScript be used in the line that starts with $sql =? var southWestLat = map.getBounds().getSouthWest().lat(); var southWestLng = map.getBounds().getSouthWest().lng(); var northEastLat = map.getBounds().getNort ...