Combine two sets of JavaScript objects based on their positions using Underscore.js

Data Set 1:

{id: "01", name: "John Doe", age: "25", city: "New York", country: "USA"}

Data Set 2:

[{key:'id', value:'01'},{key:'name', value:'John Doe'},{key:'age', value:'25'},{key:'city', value:'New York'},{key:'country', value:'USA'}]

(Screenshot)

I have two sets of data in JavaScript with the same length and I want to merge them into a single object.

[
    {key: "id", value: "01", id: "01"},
    {key: "name", value: "John Doe", name: "John Doe"},
    {key: "age", value: "25", age: "25"},
    {key: "city", value: "New York", city: "New York"},
    {key: "country", value: "USA", country: "USA"}
]

I am seeking a more efficient and faster way to achieve this using native JavaScript only.

Thank you

Answer №1

Take a look at this interesting code snippet:

let data1 = {a50: "PTP-1",b51: "09+75",c52: "112D",d53: "60.745",e54: "72.698",f55: "72.695",g56: "0.003",h57: null,i58: null, j59: "68.918", k60: null}
let data2 = [{ipid:'50', type:'Constant'},{ipid:'51', type:'Constant'},{ipid:'52', type:'Constant'},{ipid:'53', type:'Constant'},{ipid:'54', type:'Constant'},{ipid:'55', type:'Constant'},{ipid:'56', type:'Constant'},{ipid:'57', type:'Variable'},{ipid:'58', type:'Variable'},{ipid:'59', type:'Variable'},{ipid:'60', type:'Variable'}]

let results = [],
    key = '';

for(key in data1){
    if(data1.hasOwnProperty(key)){
        let currentElement = data2.filter(function(element){
            return element.ipid == key.substr(1)
        });
        for(let i = 0; i < currentElement.length; i++){
            let temporaryData = {
                ipid: currentElement[i].ipid,
                type: currentElement[i].type
            }
            temporaryData[key] = data1[key];
            results.push(temporaryData);
        }
    }
}

The above code generates the following outcome:

[
    {"ipid": "50", "type": "Constant", "a50": "PTP-1"},
    {"ipid": "51", "type": "Constant", "b51": "09+75"},
    {"ipid": "52", "type": "Constant", "c52": "112D"},
    {"ipid": "53", "type": "Constant", "d53": "60.745"},
    {"ipid": "54", "type": "Constant", "e54": "72.698"},
    {"ipid": "55", "type": "Constant", "f55": "72.695"},
    {"ipid": "56", "type": "Constant", "g56": "0.003"},
    {"ipid": "57", "type": "Variable", "h57": null},
    {"ipid": "58", "type": "Variable", "i58": null},
    {"ipid": "59", "type": "Variable", "j59": "68.918"},
    {"ipid": "60", "type": "Variable", "k60": null}
]

Answer №2

let data = {name: "PTP-1", number: "09+75", id: "112D", latitude: "60.745", longitude: "72.698", altitude: "72.695", error_margin: "0.003", category: null, type: null, value: "68.918", status: null};
let keys = [{ipid:'50', type:'Constant'},{ipid:'51', type:'Constant'},{ipid:'52', type:'Constant'},{ipid:'53', type:'Constant'},{ipid:'54', type:'Constant'},{ipid:'55', type:'Constant'},{ipid:'56', type:'Constant'},{ipid:'57', type:'Variable'},{ipid:'58', type:'Variable'},{ipid:'59', type:'Variable'},{ipid:'60', type:'Variable'}];

let transformedData = {};

for(let key in data) {
    let obj = {};
    obj[key] = data[key];
    transformedData[key.slice(1)] = { key: data[key] };
}

keys = _.map(keys, function (obj) {
    return _.extend(obj, transformedData[obj.ipid]);
});

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

I attempted to initiate a transition using JavaScript, but unfortunately it failed to execute

Hey there! I'm just starting out with HTML, CSS, and JavaScript, and I've been trying to make a transition work using JavaScript. The element I'm working with is a "menu-icon" which is a span tag with a small image nested inside another div ...

Change the hover effects on the desktop to be more mobile-friendly

In my desktop version, I have implemented some code that enables hovering over a button to display additional information or text. How can I modify this for mobile so that nothing happens when the button is tapped on? .credit:hover .credit-text, .credit- ...

Display an empty string when a value is NULL using jQuery's .append() function

To set an HTML value using the .append() function, I need to include AJAX data values. If the data set contains a null value, it will show as 'null' in the UI. I want to remove that 'null' and display it as blank. However, I can't ...

Find out the keycode of an event in ReactJS when a key is released

Whenever I try to get keyCode on a keyUp event, it always returns 0. Why is this happening? I want to avoid using keypress and similar methods, and I also need to utilize an arrow function: handleKeyPress = (e, type) => { let KeyCode = e.charCode; ...

When attempting to access an API hosted on Cloudflare from Heroku, a 403 error is returned

I am currently utilizing the Cowin API () to access available slots. My implementation is based on Node.js. Interestingly, it functions well on my local machine but encounters an error after deployment on Heroku. 2021-05-09T11:07:00.862504+00:00 app[web.1] ...

Using AXIOS and VueJs to visually represent data with a two-dimensional array

I'm new to vuejs and I want to display my data response in a two-dimensional table. This is the data I have: [{ "origine": "", "nb": 15 }, { "origine": "?", "nb": 18 }, { "origine": "?L", "nb": 1 }, { "origine": "G", "nb": 298 }, { ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

When attempting to integrate Angular 1.4's new router with components, an issue arises where a warning is triggered stating, "Failed to instantiate controller HeadlinesController

Attempting to work with Angular for the first time and struggling to load a component using data from an http request. Currently encountering a warning when attempting to execute the code with the HTTP request. Receiving a "Could not instantiate control ...

Traversing a deeply nested array of objects, comparing it with a separate array of objects

I am currently learning Javascript and facing a challenge involving looping through nested arrays of objects and filtering another array based on specific properties. Let's take a look at the structure of both arrays: const displayArr = { section ...

Is there a way to confirm whether the current date and time, based on a specific timezone and hour, is before or equal to a particular date?

I am working on a project that involves a timezone map with publishing hour in the local zone and news articles that need to be scheduled using a date picker. This particular article is set up as follows: { timeZoneId: 'Europe/Paris, releaseHour: 9 ...

Guide to configuring Winston logging with Sequelize correctly

Currently, I am setting up winston with Sequelize and have the code snippet below: const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: path. ...

Is there an alternative to the jQuery :contains selector?

How can I choose an option from a drop-down menu based on its text value? When I execute the following code: var desiredText = "Large"; $("#size option:contains(" + desiredText + ")").attr('selected', 'selected'); it ends up selecting ...

Emscripten WebAssembly: Issue with Exporting Class "Import #13 module="GOT.func" error: the module does not exist as an object or function"

Exploring the potential of WebAssembly in a project as an importable function module, I decided to dive into using C++ with Emscripten. Implementing functions was smooth sailing, but running into obstacles when it comes to classes. My goal is to expose and ...

Utilize AJAX to compare an inputted location with geocodes stored in an SQL database

Question Simplified: I am looking to compare locations stored in a database with a specific location and display results if they are within 1000m of each other. In order to provide instant results, I believe AJAX will be necessary. Current Progress and E ...

Troubleshooting Knockout.JS: Why self.myObservable is not working and the importance of code organization

My webpage uses knockout to handle a search field, dropdown selection, and page number. These elements are all initialized with default values for the first run or when the page is accessed. I'm encountering an error that says: "self.selectedTeamId i ...

Regular expression to validate the proper file naming convention: 1201_17-11-2015.zip

I am looking to verify if a specific file name follows the correct format. Here is the required format: first four numbers_two numbers-two numbers-4 numbers.zip To achieve this, I will need a regular expression. An example of a file name in JavaScript ...

Altering the innerHTML of a <p> tag with a smooth transition

I am a beginner in the world of web design. I am currently working on a project where I need to continuously change the text inside a <p> element with a transition effect similar to a slideshow. Below is the code I have so far: <p id="qu">S ...

jQuery fails to operate on products loaded through AJAX requests

Upon opening the page, jQuery functions correctly. However, when a product is loaded or changed via AJAX, jQuery stops working. I am currently using jquery-1.7.1.min.js $(document).ready(function () { $screensize = $(window).width(); if ($screensi ...

What is the process for recording information using a static method in TypeScript within a class?

For my school project, I'm struggling to retrieve the names from a class using a method. One class creates monsters and another extends it. abstract class genMonster { constructor( public id: string, public name: string, public weaknesse ...

Creating a Fresh Row - Steps to Activate Datepickr on a Copied Row

Whenever a button is pressed, a row in a table duplicates itself. Here is a snippet of the code: <tr> <td valign="top"><input type="text" name="session[]" size="15"></td> <td valign="top"><textarea name="descr[]" cols="40" ...