Develop a custom function that can take in a two-dimensional array and produce an output displaying all the key-value pairs within an object

This is a project task. Please refrain from down voting. Everyone starts somewhere, and we all have unique ways of learning.

The requirement is for the function to accept a 2D array (an array of pairs) in this specific format:

array = [[1, 2], [3, 4], ['nice', 'free'], [5, 6]]; 

The array can vary in length, but must always be in pairs as demonstrated above.

The function should return: {1:2, 3:4, nice: 'free', 5:6}

Here is the code snippet I've come up with so far:

function keyValue(array) {
    for (var i = 0; i<array.length; i++){
        var pairs = {
            [array[i][0]]: array[i][1]
        };
        console.log(pairs);
    }
}

keyValue([[1, 2], [3, 4], ['nice', 'free'], [5, 6]]);

The output displays: keyValue

(array)'returns':Object {1: 2}, Object {3: 4},  Object {nice: 'free'}, Object {5: 6}

'console.log' shows all key-value pairs, while 'return' only presents the first pair; for example {1:2}

I am unsure whether I created multiple objects with their own key-values, hence why 'return' only showed one pair

Alternatively, if I indeed created just one object, I need to utilize the 'return' function to display the complete set of key-values within that object. Any assistance would be greatly appreciated. Thank you in advance.

Answer №1

One approach is to initialize an empty object and then add properties for each item in the array.

Additionally, it's recommended to define all variables at the beginning of your code.

In simplified pseudocode, the process can be outlined as follows:

initialize empty object

loop through array
    add new key/value pair to object

return resulting object

Answer №2

This solution is quite straightforward:

function createKeyValue(array) {
var obj={};
for (let index = 0; index < array.length; index++){
obj[array[index][0]] = array[index][1];       
}
 return obj;
}

createKeyValue([[1, 2], [3, 4], ['hello', 'world'], [5, 6]]);

All you need to do is iterate through the array and assign key-value pairs to an object...

Answer №3

When you create new objects, ensure they are all separate objects. To achieve this, push each pair object into an array and then retrieve the first object using Array[0]. Here is a sample implementation:

function extractPair(array) {
var result=[];
    for (var index = 0; index<array.length; index++){
    pairs = {
[array[index][0]]: array[index][1]
    };
        result.push(pairs); // add to array
}
  console.log(result[0]) // get the first object
}

extractPair([[1, 2], [3, 4], ['great', 'awesome'], [5, 6]]);

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

Conceal a column within a table by double-clicking

I'm working on a project with a table, and I'd like to implement a feature where a column hides when double-clicked. I've seen various solutions for hiding columns on Stack Overflow, but I could use some guidance on where to add the ondblcli ...

When the phone locks, Socket.io experiences a disconnection

setInterval(function(){ socket.emit("stayalive", { "room": room }); }, 5000); I have developed a simple browser application with an interval function that is currently running on my phone. I am using Chrome on my Nexus 4 for debugging purposes. However, ...

Progress Bar Countdown Timer

I have made some progress on my project so far: http://jsfiddle.net/BgEtE/ My goal is to achieve a design similar to this: I am in need of a progress bar like the one displayed on that site, as well as the ability to show the days remaining. Additionally ...

Unable to use jQuery to update a link address

I am currently in the process of developing a Google Analytics plugin and encountering an issue with pagination that relies on Ajax. Each next and previous link triggers a request for data since it serves as the mechanism for pagination. (Problem resolved; ...

Error: Attempting to access the 'name' property of a null object

Having an issue with my Node.js server connected to MongoDB. This is the primary code for app.js: var express = require("express") var app = express(); var bodyParser = require("body-parser"); var mongoose = require("mongoose") mongoose.connect("mongodb: ...

What are the steps to incorporate npm into a Wix website editor?

Has anyone successfully installed Twilio on the Wix website editor? I can't seem to locate any console or npm. Any tips on how to get it up and running? ...

Retrieving information for a specific table row and column

Currently, I am working on fetching data from an API. I have been attempting to retrieve data using an API and have referred to this website: https://www.geeksforgeeks.org/how-to-use-the-javascript-fetch-api-to-get-data/. The data is successfully console. ...

Whenever I execute my nodejs script, I encounter the following error message: "TypeError: Cannot read property 'apply' of undefined."

I've encountered an issue in my node.js application where I have created a controller and a service. Every time I attempt to run the application, I consistently receive this error. The objective is to have a GET method that retrieves any table based o ...

Having trouble connecting the app-route with iron-selector and iron-pages

Feeling frustrated with my code. The <app-route> is functioning correctly, but the frustrating part is that the <iron-pages> just won't apply the class="iron-selected" to any of its children! index.html <app-location route="{{route}}" ...

ExpressJS and NodeJS: Troubleshooting jQuery Integration Issues

Hey there, I'm diving into Express for the first time. I've been experimenting with sessions and ajax calls, but I've hit a roadblock. Every time I launch my app, my jquery seems to be failing for some unknown reason. Here's the snippet ...

Using the PHP variable as a value rather than a reference

I'm having trouble formulating this question, which is why I'm struggling to find a suitable answer... In my function, I am assigning an existing array to a variable and then modifying that variable in the hope of updating the original array. Wh ...

Various relationships in Sails.js

Exploring associations in Sails.js beta (version 0.10.0-rc4) has been quite intriguing for me. My current challenge involves linking multiple databases to produce a unified result (utilizing sails-mysql). The association scheme I'm working with invo ...

How can I link JSON array data to a chart.js using the same canvas ID?

Here is the HTML Canvas code: <div> <canvas id="chartdiv" width="200" height="200"></canvas> </div> Below is the JSON data: [{ "SID": "1", "NAME": "niten", "FTEPERCENT": "71.29", "FTCPERCENT": "28.71" }, { ...

Disabling the shadow when setting the face color in Three.js

When creating geometric objects in my project, I am randomly setting colors on the faces: // Material used to create the mesh var material = new THREE.MeshLambertMaterial({ color: 0xffffff, ambient: 0xffffff, vertexColors: THREE.FaceColors}) function ad ...

Rendering textures in Firefox using Three.js

I am currently working on creating a plane using three.js and applying a texture to it. The texture itself is generated from a canvas element. Interestingly, I have encountered some compatibility issues with Firefox specifically, as other browsers like IE ...

How can PHP handle JSON data that arrives in an incomplete format?

I have created a basic website application that interacts with an API to gather backlink data for any website entered by the user. The API sends data in JSON format, consisting of strings and numbers. After parsing the response, I filter out the desired da ...

Incorporate new content into an element within a JavaScript array

I need help with the following code: let options = new Array("text1","text2"); I am trying to add additional text to each element in the array, so it becomes Array("text1 someothertext","text2 sometext"); Your assistance is greatly appreciated. ...

Utilizing browser and CDNs to import modules in threejs and three-globe for seamless integration

As I delve into the world of threejs and three-globe, I encounter a challenge when trying to integrate them using CDN distributions from unpkg. The issue lies in dealing with modules, and I'm considering the possibility of incorporating a build tool d ...

selenium webdriver is having trouble advancing beyond the loading stage of a javascript table

I am in the process of creating a web scraping tool to extract public data from a specific website's table Below is the code I have written for this purpose: options = webdriver.ChromeOptions() options.add_argument('--headless') driver = we ...

The proper way to send an email following an API request

I am currently developing an express API using node.js, and I want to implement a feature where an email is sent after a user creates an account. I have tried various methods, but none of them seem to be the perfect fit for my requirements. Here is some ps ...