Merging two arrays to create a JSON object

column_names: [
    "School Year Ending",
    "Total Students",
    "American Indian/Alaskan Native: Total",
    "American Indian/Alaskan Native: Male",
    "American Indian/Alaskan Native: Female",
    "Asian/Pacific Islander: Total",
    "Asian/Pacific Islander: Male",
    "Asian/Pacific Islander: Female",
    "Hispanic: Total",
    "Hispanic: Male",
    "Hispanic: Female",
    "Black: Total",
    "Black: Male",
    "Black: Female",
    "White: Total",
    "White: Male",
    "White: Female"
],
data: [
    "2012-09-30",
    3362957,
    39639,
    20253,
    19386,
    182697,
    94104,
    88593,
    696081,
    354910,
    341171,
    536271,
    250720,
    275551,
    787683,
    140593,
    100090
]

Is there a method to transform these JSON arrays into an object structure? For example:

"School Year Ending": "2012-09-30",
"Total Students": 3612108,
...

I would like to accomplish this using a lo-dash function for ease. Is this possible?

Answer №1

Combine the column_names with data using _.zipObject();

That should get the job done.

Answer №2

Implementing vanilla JavaScript - Interactive Example

const header_titles = [
    "Last Updated",
    "Total Users",
    "Male Users",
    "Female Users"
],
user_data = [
    "2022-08-15",
    10245,
    4723,
    5522
],
user_info = {};

for (let i = 0; i < header_titles.length; i++) {
    user_info[header_titles[i]] = user_data[i]
}
console.log(user_info);

Answer №3

Absolutely. I am confident that this solution will work using pure JavaScript.

let columns = { };
for (let index in column_names) 
    columns[column_names[index]] = data[index];

Check out the JSFiddle example here

Answer №4

Here's another solution using vanilla JS! This example utilizes the forEach method

Click here to see the code in action

school_data = {
    column_names:
    [
        "School Year Ending",
        "Total Students",
        "American Indian/Alaskan Native: Total",
        "American Indian/Alaskan Native: Male",
        "American Indian/Alaskan Native: Female",
        "Asian/Pacific Islander: Total",
        "Asian/Pacific Islander: Male",
        "Asian/Pacific Islander: Female",
        "Hispanic: Total",
        "Hispanic: Male",
        "Hispanic: Female",
        "Black: Total",
        "Black: Male",
        "Black: Female",
        "White: Total",
        "White: Male",
        "White: Female"
    ],
    data:
    [
        "2011-12-31",
        3471888,
        39433,
        19926,
        19507,
        182697,
        94104,
        88593,
        686081,
        344910,
        341171,
        536271,
        260720,
        275551,
        1970983,
        1006592,
        964391
    ]
}

var new_object = {};

school_data.column_names.forEach(function(el, index, data_array){
    new_object[el] = school_data.data[index];
});

console.log(new_object);

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 wrap a call to XMLHttp Request within a $q promise?

I am trying to figure out how to wrap the following code in an AngularJS ui-router resolve section with a $q promise. The goal is to return success or fail based on whether the http request works. Should I encapsulate all of this inside a promise or just ...

Incorporating an offset with the I18nPluralPipe

Having trouble with my multiselect dropdown and the text pluralization. I attempted to use the I18nPluralPipe, but can't seem to set an offset of 1. ListItem = [Lion, Tiger, Cat, Fox] Select 1 Item(Tiger) = "Tiger", Select 3 Item(Tiger, Cat, Fox) = ...

Typescript - unexpected behavior when using imported JavaScript types:

I am struggling with headaches trying to integrate an automatically generated JavaScript library into TypeScript... I have packaged the JavaScript library and d.ts file into an npm package, installed the npm package, and the typings modules in the TypeScr ...

merging 4 arrays in a specified order, organized by ID

i have below 4 array objects var dataArray1 = [ {'ProjectID': '001', 'Project': 'Main Project 1', 'StartYear': '2023', 'EndYear': '2023', 'StartMonth': 'Sep&apo ...

What is the best way to add JSON data to a table?

I have developed a php script to create json data. However, I am facing an issue while trying to display this generated json data in a table. While my php code successfully generates the data, it is unable to insert it into the table. I would appreciate an ...

Something is seriously wrong with the datetime in fullcalendar JavaScript

I've been diving into a tutorial for creating a calendar scheduler in asp.net MVC5 from this link. One issue I'm facing is the datetime being passed and stored as the min value in the database (1/1/0001 12:00:00 AM), almost like it's null b ...

I'm having trouble accessing the outcome from within the function

Having trouble getting the result to return inside a function for my basic rock paper scissors game. I've tried everything, including console logging the compare and putting it inside a variable. Strange enough, console.log(compare) is returning und ...

Encountering an unusual issue: Unable to access undefined properties (specifically 'get')

I'm struggling to get the order history screen to display the order history of a specific user. Every time I navigate to the path, I encounter the error mentioned in the title. I double-checked the path for accuracy and made sure there are no spelling ...

Using the Gmail API to retrieve the access token details by extracting the "code" parameter from the URL of a pop-up window

I am currently in the process of authenticating Gmail using OAuth2 for my web application. Upon receiving a URL from the server, the client opens a pop-up window with the following code: var win = window.open(data.google_oauth_url, `<h1>Gmail ...

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

Does writing JavaScript code that is easier to understand make it run slower?

While browsing the web, I stumbled upon this neat JavaScript program (found on Khan Academy) created by another user: /*vars*/ frameRate(0); var Sz=100; var particles=1000; scale(400/Sz); var points=[[floor(Sz/2),floor(Sz/2),false]]; for(var i=0;i<part ...

Creating a dynamic cascading dropdown list with Vue.js: Step-by-step guide

I successfully implemented a dropdown list using Vue.js, but now I want to add another similar list. How can I set this up? Here are the codes for both dropdown lists: var addUserVue = new Vue({ el: "#app", data: { heading: "Vue Select Cas ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

Tips for removing the current item from a list by clicking on a close icon of the same class name

Is there a way to remove a list item after clicking on its close icon? I am using a JavaScript function to add items to the list. Please refer to the image and code below. Thank you! https://i.stack.imgur.com/aeASd.png The code snippet is as follows: f ...

Decoding a singular object using Gson

The following is a JSON object: { user: { id: 1 avatar_url: "default.png" first_name: "Example" last_name: "User" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c5c3d5c ...

Vue select component not refreshing the selected option when the v-model value is updated

Trying to incorporate a select element into a Vue custom component using the v-model pattern outlined in the documentation. The issue at hand is encountering an error message for the custom select component: [Vue warn]: Avoid directly mutating a prop as i ...

Navigating through images within my application

When setting images, I encounter an issue where the second image overlaps the first one instead of appearing separately. How can I ensure that each image is displayed in its own box? I have attempted to use a blob directly by returning imgUrl in the showI ...

Utilizing HTML documents instead of images in Owl Carousel 2

I am currently utilizing owl carousel 2 to construct a basic sliding carousel. However, I am only using images at the moment and would like to incorporate HTML files instead. These HTML files contain multiple divs where images can be inserted, and instead ...

How to extract JSON data enclosed within HTML tags in Android application

My issue is slightly different than what I expected when I previously asked: Parse JSON to configure android application. I am receiving a JSON object from the server, and when I view it in the browser's source code, this is how it appears: JOSON.co ...

Button appears and disappears sporadically while browsing in Safari

I created a slider using SCSS, JavaScript, and HTML. You can view the demo at this link: https://jsfiddle.net/rr7g6a1b/ let mySlider = { initializeSlider: function (options) { let slider = options.container; let slides = slider.querySelectorAll( ...