Obtaining an array of objects through the reduction of another array

Currently, my goal is to extract an array of objects from another array. Let's say I have an array consisting of strings:

const strArr = ["Some", "Thing"];

The task at hand is to create a new Array containing 2 objects for each string in the original strArr. This means that the output should look like this:

result:
[{first_key: "Some"}, {second_key: "Some"}, {first_key: "Thing"}, {second_key: "Thing"}]

I have already achieved this using the following code snippet, however, I am aiming to do it without relying on let:

const numeros = ["some", 'thing']
let arr = [];
numeros.map(valor => {
    const titleContains = {
      title_contains: valor,
    }
    const bodyContains = {
      body_contains: valor,
    }
    
    arr.push(titleContains);
    arr.push(bodyContains);
});

console.log(arr)

Although the code above delivers the correct result, the usage of map may not be entirely accurate and I find myself resorting to the use of let, which is something I would prefer to avoid.

Answer №1

Utilizing the Array#flatMap method, you can generate two objects for each value.

const
    data = ["Some", "Thing"],
    result = data.flatMap(item => [{ first_key: item }, { second_key: item }]);

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

Answer №2

Check out this alternative version using the reduce method, more information can be found here

const numeros = ["some", 'thing']
const arr = numeros.reduce((acc, valor) => {
    const titleContains = {
      title_contains: valor,
    }
    const bodyContains = {
      body_contains: valor,
    }
    
    acc.push(titleContains);
    acc.push(bodyContains);
    return acc;
}, []); // <==== remember to pass an empty array here.

console.log(arr)

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

React - Attempting to access property X from an undefined variable

Trying to access the string in section1.text, but my console is showing: https://i.stack.imgur.com/ox8VD.png Here's the JSX code I'm using: return ( <div> <h1>{this.props.article.title}</h1> ...

What is the way to retrieve the value of a key-value pair in an array variable using JMeter?

After extracting the variable (userID_ALL) which holds key-value pairs of various users, I am looking to create a foreach loop that will trigger an API call using each user's ID. Is there a method to retrieve the user's ID within the foreach loop ...

Tips for handling the accent mark (diacritic mark)

My primary language is Spanish, which means I use accent marks quite frequently (á, é...). When I need to type them out, I resort to using &aacute;, &eacute;, and so on. However, I'm facing an issue when trying to compare two sentences in m ...

The state remains constant upon clicking

Below is the code snippet of my component: import React from "react"; import { useState } from "react"; import { Text, SvgContainer, Svg, Flex } from "../lib/styles"; import Modal from "./Modal"; const Credits = () ...

What steps should I take to customize WebStorm so that it no longer automatically imports the entire Typescript paths?

Recently, I noticed a change in WebStorm after an update that affected how paths were imported in my files. Initially, when typing @Component and letting WebStorm automatically import the path, it would use the following format: import { Component } from ...

Navigate through a list of data in JSON format

After successfully implementing a jQuery AJAX call, I encountered difficulty in parsing the returned value. Working with a MySQL database, I am returning a PHP array() to my jQuery AJAX function using echo json_encode($reservationArray); Upon appending th ...

Tips for updating the Google Map Key from a JAVASCRIPT script in DJANGO using a personalized variable

Is there a way to securely hide my Google Map API key in the JavaScript code? The key is dynamically generated from Django settings. I am uncertain about the proper implementation using JavaScript and src. settings.py GOOGLE_MAP = "XZZZZZZX" v ...

Adding the p5.js library to Stackblitz IDE: A step-by-step guide

Recently, I've been using Stackblitz as my IDE to improve my coding skills on my Chromebook. While it has been effective in many ways, I have encountered difficulties when trying to integrate the p5 library. As a beginner in programming, I only grasp ...

What's the most effective method for implementing a stylesheet through Javascript in a style switcher?

I've been tackling the challenge of creating a style switcher for my website. Through utilizing .append() and if and else statements, I managed to make it work successfully. Take a look at the code below: HTML <select name="active_style" id="lol" ...

The mapDispatchToProps function is failing to work, throwing an error: Uncaught TypeError: _this.props.addCountdown is not a function

Currently, I am facing an issue while working on my first app. The problem arises with a form component that should send an object via an onSubmit handler. onSubmit = (e) => { e.preventDefault(); this.props.onSubmit({ title: ...

JavaScript form with radio buttons

I'm completely new to JavaScript and I'm attempting to create a basic script that will show one form when a radio button is checked, and another form when the second radio button is clicked (with no form displayed when neither is selected). I kno ...

Interacting with the DOM of an iFrame from a separate window using Javascript

My main webpage is hosted on "DomainA" and it contains an iFrame sourced from "DomainB". Within this iFrame, there is a click event that opens a new window, also sourced from "DomainB". I am attempting to update an input field within the iFrame from the n ...

Implementing a redirect and setting a background image dynamically in ASP.NET using code-behind

I have a section in my PHP template with a onclick event handler. My goal is to redirect users to another page when they click on this section. Here's what I've attempted: HTML: <section id="header" onclick="window.location.href='Anoth ...

How to refresh a page manually in Angular 2

How can I have a page in Angular reload only once when a user visits it? This is my attempt: In the homepage component, I added the following code: export class HomepageComponent implements OnInit { constructor() { } ngOnInit() { location.relo ...

Saving an array in MySQL using PHP

As I am still in the process of learning PHP, MySQL, and a few other programming languages, I have also been working on creating a browser game. One of the features I am trying to implement is a "battle log" that records each fight that occurs, allowing u ...

Guide on transferring information from .ejs file to .js file?

When sending data to a .ejs file using the res.render() method, how can we pass the same data to a .js file if that .ejs file includes a .js file in a script tag? // Server file snippet app.get('/student/data_structures/mock_test_1', (req, res) = ...

bind a class property dynamically in real-time

I need to dynamically generate a TypeScript class and then add a property to it on the go. The property could be of any type like a function, Promise, etc., and should use this with the intention that it refers to the class itself. let MyClass = class{ ...

Add retrieved data from Modal to an array in a Laravel Controller

While working with my modal in the controller to retrieve data from a MySQL database, I encountered an issue. The query that runs multiple times and the retrieved data needs to be stored in a single array. However, the data is not being stored in the desir ...

Preserving items post-parse query in cloud code

Currently, I am in the process of developing Parse Cloud Code to retrieve JSON data from a third-party API. My goal is to make modifications to the data, check if it already exists, and save it if it doesn't. However, I am encountering difficulties in ...

Node.js put method fails to properly update the model in the database

Even though the code runs without any errors in the console, the field 'check' still doesn't change to true state. Why could this be happening? apiRoutes.put('/intake/:id', function(req, res) { var id = req.params.id; Intake. ...