Mapping two objects and an array in Javascript can be achieved by utilizing the `map()` method

I have an object and array with a response from my server that I need to convert to another format in order to display the value on the website. Do I need to use object mapping or parse JSON for this? If so, can someone please help?

{"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]}
,

Convert the above to the following:

'{"SEOUL" : "38", "BUSAN" : "CAPITAL", "NAMPODONG" : "M31"}'

var finalObj = {};
response.header.forEach(function(item, index) {
finalObj[item] = response.data[0][index];
});

The code above works fine by creating a variable and looping through the header to get its value and print it in html. The header and data are retrieved from the server, so when I enter something like "A", it will look for the SEOUL header and print 38 in the table below.

key value : A

header : SEOUL BUSAN NAMPODONG

data : 38 CAPITAL M31

I have a lot of data in the database, the above is just an example. So let's say I enter B, which is not in the database, I want to see the value "Not found" printed in html. However, this code currently prints nothing, so I am unsure if it is being processed correctly.

Answer №1

In this code snippet, a variable is created to store the values of an object's properties. The code then loops over the keys in "myObj.header" and retrieves the corresponding values from "myObj.data[0]". These key-value pairs are stored in a temporary object called tempObj, which is displayed in the console at the end.

var myObj = {
  "header": ["SEOUL", "BUSAN", "NAMPODONG"],
  "data": [
    [38, "CAPITAL", "M31"]
  ]
}
var tempObj = {};
myObj.header.forEach(function(item, index) {
  tempObj[item] = myObj.data[0][index]
})
console.log(tempObj)

Answer №2

Upon receiving from the server, it appears to be a JSON string.

This scenario involves two arrays that need to be combined into an object using the reduce method. Here is one way to achieve that:

const object = JSON.parse('{"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]}');

const result = object.header.reduce(function(accumulator, element, i){
  accumulator[element] = object.data[0][i]; // Since there was a nested array, the first element needed to be accessed.
  return accumulator;
}, {});
console.log(result);

If the nested array within the data attribute is intentional and not a formatting error, you would need to map its elements before proceeding with the reduce operation.

Answer №3

To achieve this, you can utilize the zipObj function found in the Ramda library.

Here is an example of how the code would appear:

const result = {"header":["TOKYO","KYOTO","OSAKA"],"data":[[25,"METROPOLIS","K24"]]}

const object = R.zipObj(result.header, result.data[0])
console.log(object)
<script src="//cdn.jsdelivr.net/npm/ramda@latest/dist/ramda.min.js"></script>

Answer №4

To transform the new data into objects with specific keys, you can utilize a mapping technique.

The output will be an array of objects, given that your information is stored in a nested array structure, even though it appears that there could potentially be multiple rows of data.

var data = { header: ["TOKYO", "OSAKA", "SHIBUYA"], data: [[42, "METROPOLIS", "M21"]] },
    result = data.data.map(item => Object.assign(...data.header.map((key, index) => ({ [key]: item[index] }))));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №5

To convert the array of arrays stored in the data variable into an array of objects, you can iterate over each sub-array and use the strings in the header array as keys:

function restructureData(inputObj) {
  return inputObj.data.map(function(subArray) {             
    return subArray.reduce(function(obj, value, index) {       
      obj[inputObj.header[index]] = value;                        
      return obj;
    }, {});
  });
}

var inputObj = {"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"], [10,"OTHER","M01"]]};
var modifiedData = restructureData(inputObj);

console.log(modifiedData);

Answer №6

While the responses provided above are indeed helpful, allow me to present an alternative solution that utilizes the reduce method.

var example = {
  "categories": ["FRUITS", "VEGETABLES", "DAIRY"],
  "details": [
    [10, "APPLE", "BANANA"]
  ]
};

var output = example.categories.reduce(function(accumulator, value, index) {
    accumulator[value] = example.details[0][index];
    return accumulator;
}, {})

console.log(output)

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

Is there a way to use Jackson to deserialize JSON into a Map<String, Object> as a member variable in Java?

My task involves mapping JSON data to a Box object: { "created_date": "2015-11-11", "generation_date": "2015-11-12T20:35:00+0000", "values": { "MORNING": 13, "EVENING": 18, "NOON": 446, "NIGHT": ...

How come HTML components are able to immediately access the updated value of useState, even though it operates asynchronously?

Why does useState update immediately inside HTML codes but only on the next render in functions? import { useState } from 'react' function uniqueFunction() { const [data, setData] = useState('previous') function submit(e) { <-- ...

The full execution of Jquery show() does not pause until it finishes

Here is the sequence I want to achieve: Show a div element with the CSS class yellow Execute a function for about 5 seconds Remove the yellow class and add the green CSS class "state Ok" However, when running my code, the div container does not appear u ...

Unable to locate a declaration file for the 'mymodule' module

After attempting to import my test module by installing it with npm i github.com/.../..., the code is functioning properly. However, when I opened it in VSCode, an error message popped up: Could not find a declaration file for module 'estrajs'. & ...

Coinciding titles within flot pie chart

I am facing an issue with overlapping labels in my pie charts generated using jquery flot, especially when the chart pieces are very small. Is there a recommended solution to prevent this overlap? Below is the configuration for my current pie chart: ser ...

Dealing with null values in JAXB (MOXy) unmarshalling

I am encountering issues with JSON unmarshalling using JAXB MOXy. Here is the JSON data I need to parse: { "accounts": [{ "description": "A", "balance": 1000, "balanceAvailable": 1000 }, { "description": "B", ...

Hide the selection box when hovering over the Div

Looking for a quick solution. I want the option drop down to close when another div element is hovered over. First, open the drop down and hover over the red element on the right side. When hovering over the red element, I would like the drop down to clos ...

Is there a way to programmatically prevent the back button from functioning if the previous route pathname in React was 'Login'?

When it comes to navigating back on previous pages, the traditional back button is typically used instead of relying solely on the navigation bar. However, I am currently looking to disable this feature specifically when the next previous route in line is ...

Error: When attempting to utilize the Image-Slider, an issue arises with reading the property 'classList' which is undefined

I am currently in the process of developing a website using Strapi as my CMS and Next.js(React) for the frontend. The website features an image slider that includes images, headlines, and descriptions. However, I have encountered an issue where after spen ...

Develop the react application: Determine the script tag URL based on the environment

We are working on a React application built with create-react-app. In order to incorporate an external script, we need to add a script tag within the head section of the public/index.html file. The provider of the script has given us two different snippet ...

What is the best way to use jQuery to show the initial hidden div that has a targeted class?

Let me explain my current dilemma... <div class="nested_fields"></div> <div class="nested_fields" style="display: none;"></div> <div class="nested_fields"></div> <div class="nested_fields"></div> <div cla ...

Issue with error handling while using HTML5 geolocation in Chrome browser

I have a basic map that is supposed to load centered on the user's current location if they allow HTML5 geolocation. There is a fallback function in place for users who choose not to share their location, but it seems to be malfunctioning. Here is th ...

Tips for optimizing ajax performance and creating a speedy ajax-loaded reply text field, similar to the one on Orkut

Greetings, I am currently working on a website where I would like to implement a reply user feature. How can I create an ajax loaded reply text field that behaves like a popup? Right now, the existing text field takes quite a long time to load when clicki ...

What is the best way to JSON serialize a Django queryset in python?

When working with AJAX responses, I encountered an error while trying to serialize a queryset. The error message was: TypeError: 'Font: FontName' is not JSON serializable The code snippet using JSON response looks like this: ... return Json ...

The Laravel application is unable to accept the data packaged in JSON format

I have a form with multiple fields. I want Laravel to receive the information in JSON format, but my code is not working properly. I believe there may be an issue with my "modalScript.js" file. Can you please help me fix it? Here is my controller: public ...

Is there a way to access data from a previous useState hook in a subsequent useState hook?

For my current project, I am working on developing a small marketplace website that integrates with stripe Checkout. The tutorial I was following did not cover using products from an API, which is where I encountered some difficulties. The table in the AP ...

Leverage jQuery deferred objects to handle a dynamic amount of AJAX requests

When faced with multiple ajax requests, how can I execute them using deferreds? This is my approach: //qty_of_gets = 3; function getHTML(productID, qty_of_gets){ var dfd = $.Deferred(), i = 0, c = 0; // hypothetical cod ...

Is it guaranteed that my callbacks will be executed sequentially and in order when iterating with a for loop in Node.js?

Sorry for the vague title, but I often encounter this issue and wonder about the best approach to handle it: I have an array or list that I want to iterate through and call methods with callbacks. Will all the callbacks be executed? And will they be done ...

Expanding nested content with jQuery and JSON

Currently, I am attempting to utilize a jQuery nested accordion in conjunction with a JSON object. Even though I have managed to construct the hierarchy as intended, I am encountering an issue where the entire accordion collapses upon clicking a child ele ...

How to use jQuery to dynamically add a variable to a request in Laravel 5.2

Is it feasible to append a variable to the Laravel cookie in the client using jQuery? Understandably, the Cookie is linked to the request during GET? Can you include a variable in the $request container in Laravel 5.2 using jQuery before initiating a GET ...