Setting a variable as a property of an object when utilizing the map method of Array.prototype

While working with an array of arrays and using .map(), I encountered a problem trying to assign the inner arrays as key-value pairs in an object. Despite several attempts, it wasn't successful. I'm wondering if I need to adjust my approach by breaking it down into more steps or using additional functions and variables.

I experimented with different syntax variations for the assignment element without any luck.

Even when trying arr.map(function() {}) syntax, there was no change in the outcome.

const smallArr = [1, 23, 25, 46, 52, 789, 64];

const thisArr = [5, 4, 65, 24, 35];

const thatArr = [{key: 1, anotherKey: 2}];

let parentObj = {};

const bigArr = [smallArr, thisArr, thatArr];

const newSomething = bigArr.map(arr => parentObj["arr"] = arr);

// The current parentObj output is: { arr: [ { key: 1, anotherKey: 2 } ] }

The issue seems to be related to the string representation of the element being assigned every iteration, leading to overwriting values. Consequently, the final object contains only one key-value pair, where the value corresponds to the last inner array in the outer array.

const newSomething = bigArr.map(arr => parentObj.arr = arr);
  // returns { arr: [ { key: 1, anotherKey: 2 } ] }

const newSomething = bigArr.map(arr => parentObj['arr'] = arr);
  // returns { arr: [ { key: 1, anotherKey: 2 } ] }

I am particularly puzzled by the behavior in the last example.

const newSomething = bigArr.map(arr => parentObj[`${arr}`] = arr);
  // returns { 
        '1,23,25,46,52,789,64': [ 1, 23, 25, 46, 52, 789, 64 ], 
        '5,4,65,24,35': [ 5, 4, 65, 24, 35 ], 
        '[object Object]': [ { key: 1, anotherKey: 2 } ], 
         arr: [ { key: 1, anotherKey: 2 } ] 
        }

The following example leaves me completely perplexed.

const newSomething = bigArr.map(arr => parentObj["`${arr}`"] = arr);
  // returns { 
        '`${arr}`': [ { key: 1, anotherKey: 2 } ], 
         arr: [ { key: 1, anotherKey: 2 } ] 
         }

My goal is to achieve the following structure:

parentObj = {
    smallArr: [1, 23, 25, 46, 52, 789, 64],
    thisArr: [5, 4, 65, 24, 35],
    thatArr: [{key: 1, anotherKey: 2}],
}

Answer №1

One way to simplify your code is by using object literal shorthand properties. You can learn more about it here.

let smallArr = [1, 23, 25, 46, 52, 789, 64];
let thisArr =  [5, 4, 65, 24, 35];
let thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr, thisArr, thatArr,}

console.log(parentObj)

Answer №2

To make it more explicit, you can assign each variable individually:

const smallArr = [1, 23, 25, 46, 52, 789, 64];
const thisArr = [5, 4, 65, 24, 35];
const thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr, thisArr, thatArr };

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

The above code is essentially a short way of writing:

const smallArr = [1, 23, 25, 46, 52, 789, 64];
const thisArr = [5, 4, 65, 24, 35];
const thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr: smallArr, thisArr: thisArr, thatArr: thatArr };

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

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

Merge two arrays of the same size to create a single array of strings

Looking to merge the values of two equal-sized arrays and create a third array like the one shown below. I'm in need of guidance as I have not been able to locate a built-in JavaScript method for this specific task. The goal is to construct an array o ...

Is there a way I can maintain the active state after clicking on a link?

Is there a way to maintain an active element state when navigating to another page after clicking a link? I am wondering if it is possible to use JavaScript to remove the active state from one link and apply it to the next one. I am facing some challenges ...

Experiencing a lack of output when splitting a string using Selenium

Having trouble with a selenium javascript code that splits a string? Here's the specific code: <tr> <td>storeEval</td> <td>var dList = '${StaffAdminEmail}'.split('@'); </td> <td>dspl ...

A pair of variables combined within a set of single quotation marks

After exploring numerous examples, I am still struggling to include a variable inside quotes. This situation seems unique and difficult to resolve. Take a look at the code snippet below: Var x='http://www.xyzftp/myservice/service1.svc' Var y=&a ...

Using jQuery to target a specific HTML element by its ID, not requesting the entire webpage

Currently, I am attempting to utilize jQuery ajax to fetch a project page. In this scenario, the xhr variable is expected to hold the correct string to the webpage (the target page). I have set up a condition to prevent the page from loading as a mobile v ...

Decoding the JSON Feedback in AngularJS

Recently, I started delving into Angular Java scripting and have been experimenting with calling a web service and utilizing the returned JSON in a Controller as seen below: var nameBarcodePrjList = []; var url = $rootScope.BaseURL + "PROJECT"; var conf ...

Selecting dynamic attributes in VueJS - clearing out previous selections

The data attributes are pulled from an API and the names of the attributes are dynamic. However, for the sake of simplicity, I have included an example with an object containing Colour and Size. My main goal was to map the data to an object named selectedA ...

Is Firefox triggering setTimeout function prematurely (or is Date.getTime() inaccurate)?

Encountered an unusual issue with setTimeout() in Firefox 12. It doesn't always seem to wait the correct amount of time. Could it be a problem with the date's milliseconds? Take a look at this fiddle. Setting a setTimeout for 100ms seems to exec ...

Is there a way to extract a particular string from a text file and store it in an Array using C?

I am facing a couple of issues with this code that I wrote and I'm not sure why they are happening: 1) The code is copying strings from the text file into the Odd parts of the Array (e.g. lines[3] or lines[5]). 2) It seems like the code doesn't ...

Gradually vanishing words while they glide across the screen

I want to achieve a similar effect seen in the game A Dark Room. The text in the game serves two purposes which I am trying to replicate: The new text is added above the old text instead of below it, pushing the older text down the page as the game progr ...

Switching JavaScript object with numerical keys into an array

Upon receiving a JSON response from the server, it looks like this: { "0": "1", "1": "2", "2": "3", "3": "4" } I aim to transform it into a JavaScript array as shown be ...

unable to perform a specific binary operation

Is there an efficient method to achieve the following using binary operations? First byte : 1001 1110 Second byte : 0001 0011 Desired outcome : 1000 1100 I am looking to reset all bits in the first byte that correspond to bit values of 1 in the secon ...

Navigate back to the previous slide utilizing slick and jquery

I am facing an issue with my slides that have multiple calls to actions opening different slide on click For example, if a user is on slide number 1 and clicks a button to open slide number 5, then upon clicking the go back button it should return to slid ...

The ipcRenderer.on() function is not receiving the mainWindow.webContents.send() message

Within the electron main.js file, my goal is to send an event from a child Window to a mainWindow. My initial plan was to achieve this by triggering an event from the childWindow to the Main Process, and then having the Main Process send an event to the ma ...

Combining multiple datasets in Javascript with a constant value of [0] to calculate the sum

Being a beginner, I am seeking assistance with my variable chartdata that serves as a basis: var chartdata = { labels: [ "Bar 1", "Bar 2", "Bar 3", "Bar 4", ], datasets: [ { label: "Green data", type: "bar", dat ...

Approaches to Transforming JSON Data into Another JSON Format

When it comes to converting one JSON structure into another, there is often a need for a same-format transformation. But before diving into the implementation, it's essential to understand the theoretical foundations. So, my question to you is: what a ...

Comparing elements in a Perl array

Just starting out with Perl programming and trying to figure out how to compare elements in two arrays. Here's the code I have so far: #!/usr/bin/perl use strict; use warnings; use v5.10.1; my @x = ("tom","john","michell"); my @y = ("tom","john","mi ...

Angular 4/5 | Custom Dropdown Component

I have been working on a custom dropdown directive in Angular that I can attach to any DOM element. Below is the code for my directive: import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[appDropdown]' ...

React app version displaying incorrect links to CSS and JS files

I have been immersed in a React project called Simple-portfolio, you can find the GitHub repository here: https://github.com/Devang47/simple-portfolio and the live site at this URL: While everything works smoothly on the development server, I encountered ...

How can multiple buttons be added to each row in Jquery datatables and how can events be applied to them?

I currently have one button, but I am in need of two buttons. These buttons will trigger MySql commands when clicked to retrieve data from the database. How can I set up an event handler for these buttons? $(document).ready(function () { var table= ...