JavaScript Object Notation is a standard way of formatting

After performing some manipulations, I have stored values in arrays called 'miles' and 'type'. My goal now is to display them as an object with their own specific properties. Here's what I have so far:

obj = { 
    "miles" : [500, 200], 
    "type": ["fer", "bug"] 
};

The desired output format is as follows:

obj = { 
    "fer" : 500 , 
    "bug" : 200 
};

Thank you for any input on how to achieve this!

Answer №1

Implement a loop to create a new data structure

var obj = { "sizes" : [30, 40], "colors": ["red","blue"] };
    
var newObj = {};
    
for (var i=0; i<obj.colors.length; i++) {
    newObj[obj.colors[i]] = obj.sizes[i];
}

// Display the newly created object
document.body.innerHTML = '<pre>' + JSON.stringify(newObj, null, 4) + '</pre>'; 

Answer №2

let result = {};
for (let index = 0; index < object.type.length; index++) {
    result[object.type[index]] = object.miles[index] || 0; // Adding a default value for safety
}

Answer №3

If the lengths of both type and miles are equal, you can use the following code snippet.

const data = { "miles": [800, 300], "type": ["car", "bike"] };
let length = data.type.length;
let resultObj = {};

for (let i = 0; i < length; i++) {
    resultObj[data.type[i]] = data.miles[i];
}

The variable resultObj will store the updated output.

Answer №4

Utilizing the functionality of lo-dash's method called zipObject:

Generating an object by combining arrays containing keys and values. You can input either a single two-dimensional array, for example [[key1, value1], [key2, value2]], or two separate arrays - one for keys and another for corresponding values.

The array of keys in the .type property are linked to the values in the .miles property.

This operation can be achieved with just one line of code:

var convertedObj = _.zipObject(obj.type, obj.miles);

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

Nextjs: Issues with Dropdown functionality when using group and group-focus with TailwindCSS

My goal is to make an array visible once a button is clicked. By default, the array should be invisible, similar to drop-down menus in menu bars. I am utilizing the group and group-focus classes. While the array disappears as expected, it does not reappear ...

I am facing an issue with Ajax in Laravel, as it is displaying a page not

I'm having trouble sending OTP with Laravel and Ajax. Whenever I try to call the Ajax function, it displays an error saying "Page not found"... HTML: ` <div id="first_step"> <div class="col-md-4" ...

Tips for retrieving a value returned by a Google Maps Geocoder

geocoder.geocode( { 'address': full_address}, function(results, status) { lat = results[0].geometry.location.lat(); lng = results[0].geometry.location.lng(); alert(lat); // displays the latitude value correctly }); alert(lat); // does ...

Display a pop-up upon clicking a button

I've created a custom popup form using Flodesk and added the corresponding Javascript Snippet to my website just before the closing head tag. <script> (function(w, d, t, h, s, n) { w.FlodeskObject = n; var fn = function() { (w[n] ...

Exploring the capabilities of storing and retrieving nested objects within a React database

I'm having trouble retrieving nested items from my database. This is how my database is structured: GET /dwelling/room/ [ { "room_id": 1, "room_name": "Living Room", "room_data": [ { "id": 1, ...

Changing UUID from binary to text and vice versa in NodeJS

I recently started a project that transitioned to using MySQL as our database. We are working with UUID strings (such as 43d597d7-2323-325a-90fc-21fa5947b9f3), but the database field is defined as binary(16) - a 16-byte unsigned binary. Although I know th ...

How can I use jQuery to determine the total count of JPG files in a directory

How can I use jQuery to count the number of jpg image files in my document? Here is the command to count the image files: $('#div').html($('img').length ); However, this counts all image files with the 'img' tag. Is there ...

Fill up mongoose with data on 3 schemas

I have successfully populated 2 schema, but I am facing difficulty in populating the third schema. Here are the schemas: Member Schema var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var Schema = mongoose.Schema ...

removing a particular item from an array in Javascript

Currently, I am conducting an experiment on removing objects from an array. Please note that this code is not formal as it is intended for testing purposes. <script type="text/javascript"> // Initialize array and objects var fruits = new Array(); ...

Retrieve the HTML source code using AngularJS through an HTTP GET request

I came across a thread in the forum discussing a similar issue but unfortunately, it didn't have any answers. Let me explain my problem - I'm trying to validate a form using AngularJS and connect it by sending an HTTP request on submit. In my log ...

What is the purpose of implementing asynchronous loading for JavaScript in my webpack setup?

I am facing difficulties with handling unusual codes. I am trying to add some query parameters using $.ajaxPrefilter in all jQuery ajax requests. I came across the following code snippet which seems to ensure synchronous loading order, but in my entry.js ...

Stop the jQuery custom slide animation when there are no more items to display

I have designed a unique slider for users to view the work process https://i.sstatic.net/FLYne.png When a user clicks the button, the slider will move left or right depending on the button clicked. However, if the user clicks multiple times, the slider ma ...

JavaScript Mobile Redirect HTML

Despite numerous attempts, I have been unable to get the mobiledetector script to function as desired for my mobile viewers. My goal is to include a link on the mobile site that allows users to access the full site without being redirected back to the mobi ...

Center the image within the div by setting its position to absolute

<div class='img-box'> <img /> //position absolute <img /> //position absolute <img /> //position absolute <img /> //position absolute I am struggling to center the images within this div because of their absolute p ...

TypeORM is unable to locate the default connection within a class

I have encountered an issue while trying to incorporate TypeORM within a class. It seems to be unable to locate the default connection despite awaiting the connection. I have double-checked the configuration and tested it with .then(), which did work succe ...

Error: JSON parsing stopped due to unexpected end of file while attempting to parse data

After testing with other APIs successfully, I found that this particular one is not functioning as expected. const express = require("express"); const https = require("https"); const bodyParser = require("body-parser"); const ...

What is the best way to create a mirror effect on one div by clicking another div?

I have created a schedule grid and I am looking for a way to allow users to click on the UK hour and then have the corresponding U.S time highlighted. Is there a CSS solution for this? The functionality I need is to be able to select multiple hours. I have ...

Developing a multi-graph by utilizing several JSON array datasets

Currently exploring D3 and experimenting with creating a multi-line graph without utilizing CSV, TSV, or similar data formats. The key focus is on iterating over an array of datasets (which are arrays of objects {data:blah, price:bleh}). I am trying to a ...

How do I search for a JSON object in JavaScript?

I have an array containing screen resolutions and I need to find the correct resolution range for the user's viewport (I have the width x height of the current window). Here is the sample JavaScript array with JSON objects: [ {width:100,height:200, ...

"Concealing Querystrings in Node.js and AJAX: A Step-by-Step

I want to create a simple login form using the ajax Post method. However, I am having issues with the querystring still appearing in the URL. Can anyone help me resolve this issue? Thank you for any assistance! [ https://i.stack.imgur.com/R76O4.png http ...