An arrow function is used to return a parameter as a property of an object

My goal is to have the parameter word of my arrow function return as the property of the object key. However, the object returned currently contains the property "word".

lines = ["first row","second row","third row"]
let newLines = lines.map((item, index)=> {
                let wordsPerLines = item.split("\s");
                return wordsPerLines.map(word => ({ word : index}))
        }
        );
        console.log(newLines);

This is the current output:

[
 [
   {
     "word": 0
   },
   {
     "word": 0
   }
 ],
 [
   {
     "word": 1
   },
   {
     "word": 1
   }
 ],
 [
   {
     "word": 2
   }
 ]
]

I am aiming for this desired output instead:

[
 [
   {
     "first": 0
   },
   {
     "row": 0
   }
 ],
 [
   {
     "second": 1
   },
   {
     "row": 1
   }
 ],
 [
   {
     "third": 2
   },
   {
     "row": 2
   }
 ]
]

Answer №1

In order to specify the property name, make sure to enclose it in square brackets:

word => ({ [word] : index})

Therefore:

return wordsPerLines.map(word => ({ [word] : index}));

The [ ] can hold any expression. This will be evaluated and the resulting string value will be used as the property name.

Answer №2

When working with Javascript, it's important to remember that object keys are taken literally. If you want to use a variable instead of a static value, you can modify your return code as shown below:

return wordsPerLines.map(word => ({ [word] : index}))

By enclosing the variable in brackets, you're indicating to Javascript that it should interpret it as such, rather than a fixed string like 'word'.

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

Does Leaflet.js provide a method to cycle through all markers currently on the map?

Is there a way to make my map icons scale in size with zoom instead of being a static 38x38? If CSS can achieve this, I'm open to that option as well. It seems like it would also involve iterating through all markers, but I haven't been able to f ...

I am interested in creating a JavaScript function that can transform an image to either a blue or yellow hue using CSS styling

Check out this code snippet. <svg class="defs-only"> <filter id="monochrome" color-interpolation-filters="sRGB" x="0" y="0" height="100%" width="100%"> <feColorMatrix type="matrix" values="0.00 0 0 0 0 ...

I need assistance in reading a CSV file that has been uploaded via an HTML form using jQuery. Can you provide guidance on

Currently, I am attempting to utilize jQuery in order to read a CSV file. I have implemented an input tag in HTML for the file, but I am encountering some difficulties when it comes to reading it. Below you can find the code that I have put together: HTML ...

Adjust the color of the font based on its value

Is it possible to change the color of text on a page based on a specific value? <div [ng-Style]="color":colorFont({{item.temp.day}})> {{item.temp.day}} {{vm.symbal}}</div><br> The data {{item.temp.day}} is a numerical value that determi ...

The attempt to use the executeScript command to inject a prompt and return a value was unsuccessful due to the

Currently, I am working on testing a login form using selenium. The form requires users to enter an SMS code for verification. In order to accomplish this task, I am utilizing the facebook/php-webdriver. To achieve this, I have injected the following JavaS ...

Disabling dynamic color updates upon refresh

I am currently using chartjs and I want to generate new random colors each time the page is refreshed. However, I need these colors to remain fixed and not change after a page refresh or reload. Below is the function I am working with: getRandomRgb() { ...

Ensure that the JavaScript is loaded prior to refreshing the webpage

Below is the HTML code snippet: <script src="https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap&v=quarterly" defer></script> <script src="{% static '/javascript/maplanguage.js' %}">< ...

Android browser experiences a sudden surge of unexpected data influx

I am facing an issue with my application where it maps an array from the state. The array should ideally only contain 6 sets of data, as limited by the backend. However, sometimes it spikes and displays data that is not supposed to be there or shows old da ...

Is there a way to create triangles on all four corners of an image using canvas in JavaScript?

In my code, I am currently working on drawing rectangles on the corners of an image using JavaScript. To achieve this, I first extract the image data from a canvas element. // Get image data let imgData = ctx.getImageData(0, 0, canvas.width, canvas.height) ...

Using React to dynamically set the width of a div element to match the width of an image

I am trying to ensure that my div is always the same width as the image it contains, even when the window is resized and the image adjusts automatically. I attempted to solve this using the useState hook, but it does not seem to respond to resize events. ...

What is causing my elements to display incorrect sizes upon page load?

My goal is to dynamically hide a navigation menu if there isn't enough space in the window. The navigation menu is within a wrapper that also includes a logo, and I use the following code to determine if there is sufficient room: if ($(window).width( ...

Utilizing JavaScript to retrieve data using AJAX

Having trouble sending emails through ajax on my website. The form is in a modal (using custombox), but all values being sent are null. How can I utilize getElementById in modal content? Link to custombox git's hub: https://github.com/dixso/custombox ...

utilizing a message collector for configuring embed fields

I'm currently working on a message collector feature that collects data to use in an embed's title, description, and color. My goal is to have each value correspond to a different aspect of the embed. However, I've encountered some challenge ...

Is there a restriction on the number of Chrome Webdriver instances allowed

I have been attempting to launch multiple Node instances using the Chrome webdriver on an Amazon EC2 server. However, I have encountered a problem where once I reach a total of 84 node instances, Selenium throws an error: Build information: version: &apos ...

Codeigniter 3 and Ajax: Troubles with receiving post data

I'm struggling to successfully send some data via Ajax to save it inside a controller. Unfortunately, I am unable to retrieve the posted data inside my controller as it always appears empty. Here is my basic Ajax code that just doesn't seem to w ...

Utilize the Jest moduleNameMapper for locating files: "resolver": undefined

Among the various files I have, there is a text file located in the component directory within the path: src/components/text Despite this, Jest is unable to locate the file when utilizing the webpack alias import Text from "components/text"; I ...

What kind of impact on performance can be expected when using index.ts in a Typescript - Ionic App?

When setting up the structure of a standard Ionic app, it typically looks like this: app pages ----page1 ---------page1.ts ----page2 ---------page2.ts If I were to include an index.ts file in the pages folder as follows: pages/index.ts export { Page1 } ...

I'm sorry, we couldn't find the module: Error: The file path '@mui/material/Unstable_Grid2' cannot be resolved

I encountered an issue while using Grid2 in my React Application. The error message I received is as follows: Module not found: Error: Can't resolve '@mui/material/Unstable_Grid2' I am currently utilizing MUI v5 and have followed the instal ...

Executing an onscroll function based on window.innerWidth in JavaScript

I want to trigger my scroller function only when the window width exceeds 599 pixels and the user is scrolling. The function itself works fine during scrolling, but adding an event listener seems to cause it not to work. Can anyone offer guidance on how ...

The precision of the stopwatch is questionable

Just starting out with JS and jquery, I quickly put together a stopwatch code in JS that seems to work accurately up to 10 minutes. The issue arises after the 10-minute mark where it starts falling a few seconds behind (I compared it to a digital stopwatc ...