Utilizing the spread operator to map an array within another array

Exploring the spread operator inside an array to map values from another array has led to unexpected behavior. When attempting to return 2 objects using map within the array, only the last object is being returned. Below is the code snippet:

const cats = ["Tom", "Ginger", "Angela"];

const array = [
  // {
  //   name: "Ben",
  //   sex: "male"
  // },
  ...cats.map((element, index, array) => {
    return (
      {
        name: element,
        sex: element !== "Angela" ? "male" : "female"
      },
      {
        age: element !== "Angela" ? "20" : "18",
        color:
          element === "Tom"
            ? "black"
            : element === "Ginger"
            ? "orange"
            : "white"
      }
    );
  })
];

console.log(array);

Output in console:

[{"age":"20","color":"black"},
{"age":"20","color":"orange"},
{"age":"18","color":"white"}] 

Expected output:

[{"name": "Tom", "sex": "male"},
{"age":"20","color":"black"},
{"name": "Ginger", "sex": "male"},
{"age":"20","color":"orange"},
{"name": "Angela", "sex": "female"},
{"age":"18","color":"white"}]

View on Codesandbox here. Is there a way to achieve the expected outcome or are there other alternatives?

Answer №1

When you are returning two objects in JavaScript with a comma, only the last item will be returned. To return both objects, you need to use an array and the flatMap method.

const cats = ["Tom", "Ginger", "Angela"];
const result = cats.flatMap(x => ([{
  foo: x
}, {
  bar: x
}]));

console.log(result);

Answer №2

The issue at hand was primarily due to the fact that instead of return({},{}), you should have used return [{},{}].

When you use (a,b), it is referred to as a comma expression. This evaluates the first expression a, disregards the result, and only returns the evaluation of the second expression b.

const cats = ["Tom", "Ginger", "Angela"];

const array = cats.map((element) => [{
    name: element,
    sex: element !== "Angela" ? "male" : "female"
  },
  {
    age: element !== "Angela" ? "20" : "18",
    color:
      element === "Tom"
        ? "black"
        : element === "Ginger"
        ? "orange"
        : "white"
  }]
);

console.log(array);

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

What methods can be utilized to enhance the visual appeal of a threejs model

I'm currently working on enhancing the visual quality of my 3D models, aiming for smoother edges and more realistic shadows. To achieve this, I am experimenting with an OBJ file format. Here's the code snippet I'm using to load and display t ...

A guide on updating the Date Textfield value in Material UI

In my data structure, I have an array of objects with unique ids and date values. For instance, the array named stepDates might appear like this: [ { id: 1, date: "2021-07-23" }, { id: 2, date: null }, { id: 3, d ...

React JS: Incorporating Multiple Placeholder Objects within Components

Apologies if this question is a duplicate, but I haven't found any helpful answers yet. I'm new to React and JavaScript. I am looking to include multiple objects inside a component: For example: src={url} name={text} subTitle={subtext} My in ...

How do server side cookies and javascript cookies interact with each other?

Can you explain the connection between the cookies generated by the Cookie Class in Servlet and document.cookie in JavaScript? ...

Guide on accessing a nested array with a specific key from a multidimensional array

I am currently working with an array and attempting to extract the value of the key 'Summary' from the $array variable. ["Rows"]=> array(1) { ["Row"]=> array(1) { [0]=> array(1) { ["Rows"]=> array(1) { ...

Designate material for a particular table header element

Is there a method to pass content within a td-element to a specific th-element? I am working with a dynamic table and need to associate the content correctly under each table header. I have implemented pagination for the rows in the table. Currently, all ...

Ways to refresh a canvas element without requiring a full page reload

My goal is to restart a canvas on a website without reloading the page, making the restart dynamic. However, I've noticed that after multiple restarts, the animation slows down and memory usage increases. The situation is complicated by my use of Met ...

How to initiate focus on Angular 2 MdInputContainer after the view has been

I am encountering an issue with setting focus on the first md-input-container element within a component when the view loads. Despite implementing a @ViewChild property and calling focus on it in the ngAfterViewInit method, the focus does not seem to be wo ...

Upload your existing image files to Dropzone

I have implemented image upload functionality using Dropzonejs in a form. To handle multiple form fields, I have set autoProcessQueue to false and processing it on click of the Submit button as shown below. Dropzone.options.portfolioForm = { url: "/ ...

What could be causing the syntax error I'm encountering while trying to extract data from this JSON file?

I've been encountering a syntax error in my console that reads "Uncaught SyntaxError: Unexpected token '}'. I've checked my JavaScript code, but being new to coding, I'm not sure why this is happening. Could the error be on the JSO ...

Differences in performance between Angular and JQuery_execution times

I am facing an issue on my dynamically populated Angular page. Angular sends a request to the backend using $http.get to retrieve data which then populates attributes of a controller. For example, when I call $http.get('/_car_data'), the JSON re ...

Guide on automatically opening downloaded files in a new tab in IE 11 or Edge similar to the way file downloads function in Chrome

I am currently using Windows 10 and implementing msSaveOrOpenBlob in JavaScript to download the AJAX call blob on IE11. I want the PDF file to be opened in a new tab without any prompts, similar to how it works in Chrome. However, even when trying with th ...

Creating a hash map for an iteration through a jQuery collection

Using the jQuery .each function, I traverse through various div elements. By using console.log, the following output is obtained: 0.24 240, 0.1 100, 0.24 240, 0.24 240, The first number on each line represents a factor and the last number is the res ...

Breaking down the text into key-value pairs within an array

Here is a text I have: Questions no.1 this is the answer to question no.1 Question no.2 this is the answer to question no.2 Question no.3 this is the answer to question no.3 I am looking to store these questions and answers in an array with ...

What is the best way to store user inputs in a text file using ReactJS?

I have a contact form with three input fields and I would like to save the input values into a text file when users click on a button. How can I achieve this? Can you provide an example? Here is my code: import React, { } from 'react'; import l ...

Enhancing the Ext.ux.grid.RowEditor by implementing tooltips for the save and cancel buttons

I am looking to implement tooltip messages for the save and cancel buttons in Ext.ux.grid.RowEditor. For example, I want the save button to have a tooltip that says "Save the records" and the cancel button to have a tooltip that says "Cancel saving the rec ...

A guide on customizing bar colors in a jqPlot stacked bar graph

Is there a way to customize the colors for individual bars in a jqPlot stacked bar chart? I've searched through examples, but they all seem to use the default colors. How can I explicitly set different colors for each bar? Here is the current code sn ...

Observing a peculiar discrepancy in how various versions of JSON.stringify are implemented

Imagine having a deeply nested JS object like the example below that needs to be JSON-encoded: var foo = { "totA": -1, "totB": -1, "totC": "13,052.00", "totHours": 154, "groups": [ {"id": 1, "name": "Name A", " ...

Adding 7 days to a JavaScript date

Can you spot the bug in this script? I noticed that when I set my clock to 29/04/2011, it displays 36/4/2011 in the week input field! The correct date should actually be 6/5/2011 var d = new Date(); var curr_date = d.getDate(); var tomo_date = d.getDate( ...

Encountering an excessive number of re-renders due to attempting to display a FlatList component

I am attempting to showcase a flatList of numbers similar to this: (view image example) In order to achieve this, I created an array of objects with a numberName and a key using a loop: const number = 5; let [numbers, setNumbers] = useState([]); let nums ...