In just a single line of code, you can iterate through a Record object and retrieve an array of DOM elements

I am working with an object

type MyType = 'name' | 'base' | 'six';

obj: MyType = {
  'name': {key: 'm1'},
  'base': {key: 'm2'},
  'six': {key: 'm3'},
}

My goal is to loop through obj and generate a LIST of elements like this:

<div>name,m1</div><div>base,m2</div><div>six,m3</div>

I attempted using reduce or map for this, but it didn't work as expected. This is the desired output.

Object.entries(obj).reduce((acc, key) => {return <div>key,item[key]</div>};

Answer №1

You have the option to add padding around key/value pairs.

const
    addPadding = (array, tag) => array.map(v => `<${tag}>${v}</${tag}>`).join(''),
    object = { name: { key: 'm1' }, base: { key: 'm2' }, six: { key: 'm3' } },
    string = addPadding(Object.entries(object).map(([k, { key }]) => [k, key].join()), 'div');

console.log(string);

Answer №2

const generatedHTML = Object.keys(MyType).map(key=> `<div> ${key}, ${ MyType[key]['value'] } <div/>` ).join(" ");
console.log(generatedHTML);

Result:

<div> first, value1<div/><div> second, value2 <div/><div> third, value3 <div/>

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

Attempting to incorporate Font-Awesome Icons into the navigation bar tabs

As a newcomer to React, I've been attempting to incorporate Font Awesome icons into my secondary navigation bar. Despite using switch-case statements to iterate through each element, all the icons ended up looking the same, indicating that only the de ...

If you're trying to work with this file type, you might require a suitable loader. Make sure you

Attempting to utilize Typescript typings for the Youtube Data API found at: https://github.com/Bolisov/typings-gapi/tree/master/gapi.client.youtube-v3 Within the Ionic framework, an error is encountered after running 'Ionic Serve' with the follo ...

Server Error: Reactjs doesn't support posting images

I am experiencing an issue in my ReactJS project. When I attempt to upload an image using react-images-uploader, I encounter the following error: "Cannot POST /images error" Below is the code snippet for the image upload: <ImagesUploader ur ...

Identify and forward to the mobile-friendly version of the site

I am currently working on a website that requires separate files for mobile view as the html layout poses challenges in making it responsive. My goal is to find code that can detect if the user is accessing the site from a mobile device, and automatically ...

"Execution of the console.log statement occurs following the completion of the request handling

When I have a piece of middleware that responds if no token is found, why does the console.log line still run after the request is responded to? I always believed that the res.json call would "end" the middleware. Any insights on this behavior would be g ...

I'm puzzled as to why this code snippet consistently produces a range of 50 to 100 repeated values. This piece of code is crucial for altering the behavior of a function based on a specific

Below is a snippet of my React code aiming to alter the functionality of a function based on a specific window width: const [windowWidth, setWindowWidth] = useState({ winWidth: 0 }); useEffect(() => { window.addEventListener('resize', ( ...

Recording web browser network traffic using JavaScript

Is there a method in webdriverio that allows me to capture and validate the response of API calls made by the browser while loading data for my automated tests? https://i.sstatic.net/TMExU.png ...

Trouble Arising from the Lack of Coordination Between CSS Transition and JavaScript Update Triggered by Element

I'm currently working on a web development project that involves a list of clickable elements. When one of these elements is clicked, it should become active and trigger a CSS transition (such as a transform) with a duration of 200ms. Additionally, I ...

Users are reporting that verification emails are not being sent when the Accounts.createUser function is used within

I have a simple meteor method set up to create user accounts. In my server/methods.js file: Meteor.methods({ createUserAccount: function(user) { return Accounts.createUser(user); } }); Then in my server/init.js file: Meteor.startup(function() ...

When setupFilesAfterEnv is added, mock functions may not function properly in .test files

Upon including setupFilesAfterEnv in the jest.config.js like this: module.exports = { preset: 'ts-jest', testEnvironment: 'node', setupFilesAfterEnv: ["./test/setupAfterEnv.ts"] } The mock functions seem to sto ...

Having an issue with fastify-multer where request.files is coming back as undefined during testing with Postman

In the process of developing an API that consumes multipart/form-data using fastify, I've integrated the fastify-multer plugin to handle file uploads for passing them to another third-party API. Currently, I'm testing with Postman, but encountere ...

How to manage multiple controllers for the same template in AngularJS?

I am facing a requirement where a single page needs to display a lot of different data, all within one vertical-scrolling page. To manage this, I have implemented collapsible divs on the page controlled by ng-if to efficiently handle the DOM elements. In ...

Tips for enhancing the speed of drawing circles in mouse movement using JS and CANVAS

My current script allows me to draw a circle during mousemove, but it's not as fast as I'd like. Before drawing the circle, I gather the color pixel during mousemove in order to draw a circle on the canvas with the picked color. I came across ...

The compatibility between MUI Autocomplete and react-hook-form is limited and may not function properly

Problem Description I am encountering various errors at different times. Specifically, when I try to select a suggested option, I receive the following error and warning messages: Material-UI: The getOptionLabel method of Autocomplete returned undefined ...

Checkbox input with alphabetical ordering

I am currently facing an issue with a form that has checkboxes, but the text is not in alphabetical order. While there are plenty of examples for lists, finding examples for checkboxes has been challenging. http://jsfiddle.net/fG9qm/ <form> < ...

Utilizing the .add() method in Firebase Cloud Firestore for working with nested

In the documentation for Firebase, it mentions updating nested objects. You can find out more about this here: https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects Here is my data structure: let ref = db.collect ...

Uniform Image Sizes in Bootstrap Carousel (With One Exception)

I am encountering a JavaScript exception related to image size. I am trying to set a fixed size for the images in my carousel, allowing them to auto adjust or resize without concern for distortion or pixelation. I have experimented with max-width and widt ...

What is the process for creating a multi-word argument?

Is there a way to create multi-word arguments, such as reasons for bans or mutes? Currently, I am using args[2], args[3], args[4], args[5]... but this approach is limited and if nothing is written in those arguments, it will display "undefined". If you k ...

Receiving an `Invalid module name in augmentation` error is a common issue when using the DefaultTheme in Material

After following the guidelines outlined in the migration documentation (v4 to v5), I have implemented the changes in my theme: import { createTheme, Theme } from '@mui/material/styles' import { grey } from '@mui/material/colors' declar ...

Concerns have been raised regarding the lack of light and shadows being detected by THREE.BufferGeometry in JavaScript/th

I've been trying to generate terrain using noise functions, but I'm running into an issue where the BufferGeometry mesh isn't receiving any light from PointLight. When I switch to AmbientLight, the BufferGeometry is visible, but not with Poi ...