JavaScript: Insert a new key and value at a designated index within an array of objects

I currently possess an array of Objects similar to this one.

let arr =  [{name:"abc",age:26},{name:"xyz",age:23},{name:"pqr",age:10}]

let newVal  = arr.map(function(el) {

                

                if(el.age > 25){
                    var o = Object.assign({}, el);
                    o.gender = 'male';
                    return o;

                }
              })

              console.log("New Val : " , newVal)

I am interested in appending {gender:'male'} to objects where the age exceeds 25.

However, it shows undefined for other objects.

I would greatly appreciate any assistance.

Thank you.

Answer №1

If the object does not meet the specified condition, make sure to return the value. If nothing is returned from within the map function when the condition is not met, it will result in undefined for the other objects.

let arr = [{
  name: "abc",
  age: 26
}, {
  name: "xyz",
  age: 23
}, {
  name: "pqr",
  age: 10
}]

let newVal = arr.map(function(el) {
  if (el.age > 25) {
    var o = Object.assign({}, el);
    o.gender = 'male';
    return o;

  }
  return el; // make sure to return a value here
})

console.log("New Val : ", newVal)

Answer №2

The problem in your code has already been resolved in another answer by Shubham. For example, when the if clause is not executed, nothing is returned.

However, I believe using forEach might make the code cleaner in this case.

If you wish to preserve the original array, you can make a copy of it using copyArr = [...arr]

let arr =  [{name:"abc",age:26},{name:"xyz",age:23},{name:"pqr",age:10}]
arr.forEach(function(el) {
                if(el.age > 25)
                    el.gender = 'male';
              })

console.log("New Val : " , arr)

Answer №3

The issue arises from the absence of a return statement when the condition is evaluated as false.

A more concise solution involves using an arrow function in a single line:

let arr =  [{name:"abc",age:26},{name:"xyz",age:23},{name:"pqr",age:10}],
    newVal = arr.map((el) => Object.assign({}, el, el.age > 25 ? {gender: "male"} : {}));

console.log("New Val:", newVal);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

By using the map function, you can create a new array. Within the function, you can choose to either create a copy of the object with an added property or keep the original object as it is.

let array =  [{ name: "abc", age: 26 }, { name: "xyz", age: 23 }, { name: "pqr", age: 10 }],
    result = array.map(object => object.age > 25 
        ? { ... object, gender: 'male' }
        : object
    );

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

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

Creating a custom table layout with JavaScript and jQuery

I've been grappling with a project for some time now, and I'm stuck on this particular issue. In my database, I have a table structured like this: ProjectName UserName SpentDays FirstProject User1 10 SecondProject User1 5 SecondProjec ...

What are the steps for creating personalized sliders with WordPress?

Seeking guidance on how to code WP Template files to enable control from the WP dashboard for adding or removing slider images. A sample code snippet is provided below. <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indi ...

What sets apart the method of assigning event handlers using bind() versus each() in jQuery?

Could someone explain the difference between using bind() to assign event handlers and using each() for the same task? $(function () { $('someElement') .bind('mouseover', function (e) { $(this).css({ ...

Ways to access elements and their associated values in a JavaScript Array

I'm facing a challenge with a JavaScript array where I need to extract teams (Team A, Team B) and organize them into one array while preserving their order. See below for the current output of the array, as well as the JS code provided and the expecte ...

What is the best way to set a value for a variable within a UI component in React?

I'm still learning the ropes with React and JavaScript. My current challenge involves declaring a temporary variable and assigning the value of companyData.name to it, as I need to gather data from two variables like companyData.name. Below is my cod ...

JavaScript - utilizing a confirmation dialog box within a function

My JavaScript code was working well because I received some fantastic solutions here yesterday. I am now wondering if I can enhance this JavaScript with another query. Currently, the query triggers an alert when the number is greater than 199, and it is fu ...

When the user clicks on a specific element, ensure that it is the main focus and generate an overlay

One of my challenges is implementing a custom element that captures user input upon clicking, focusing on it and overlaying other elements. I want the overlay to disappear if the user clicks outside the div. I attempted to achieve this using the iron-over ...

How to break down JSON into individual elements using JavaScript

{ "name": "Sophia", "age": "Unknown", "heroes": ["Batman", "Superman", "Wonder Woman"], "sidekicks": [ { "name": "Robin" }, { "name": "Flash Gordon" }, { "name": "Bucky Barnes" } ...

Ways to update the div's appearance depending on the current website's domain

There is a piece of code that is shared between two websites, referred to as www.firstsite.com and www.secondsite.com The goal is to conceal a specific div only when the user is on secondsite. The access to the HTML is limited, but there is an option to ...

Ways to showcase logs on the user interface

After configuring a set of operations in the UI and initiating the operation, a Python script is called in the backend. It is necessary to display the logs generated by the Python script on the UI. I managed to implement this in a similar way as described ...

Cease the execution of processes once a Promise has been rejected

My current code is functioning correctly, but I am facing an issue where if an error occurs, I want it to halt all other promises in the chain. Specifically, when chi.getCommand(val1, val2) returns a reject and triggers the exception catch block, I need to ...

``There seems to be an issue with the redirect header function in the PHP

Setting up my test site on a local host, I included an ajax request in one of my java-script files to a php script. if(hIF == "true"){ $.ajax({ type: "POST", url: "log_in/login.php", data: {name: userName, pwd: password}, ...

Problem with implementing swipeable tabs using Material-UI in React

I'm experiencing an issue in my application with the react swipeable tabs from material-ui. I followed all the installation steps recommended in the documentation. Currently, I am encountering the error shown in the screenshot below. Could there be a ...

Dynamically populating checkboxes and dynamically setting their checked state

I'm working with a for loop that dynamically generates 7 checkboxes in a row. Here's how it looks: @for (int i = 1; k < order.Rows.length; i++) { Row: @i <ul> @for (int j = 1; j < order.NumCheckboxes.length; j++) ...

Uploading CouchDB document attachments using an HTML form and jQuery functionality

I am currently in the process of developing a web form that, upon submission, will generate a couchdb document and attach file(s) to it. I have followed tutorials and visited forums that suggest a two-stage process similar to futon's approach. While I ...

The webpage continues to refresh after executing a JavaScript function triggered by the AJAX response

I have experimented with various solutions for calling a JavaScript function returned from an AJAX response. While each method worked to some extent, I found that using an alert within the refreshResults function was necessary in order to display the resul ...

ReactJS - run a JavaScript snippet once the Ajax call has successfully fetched and displayed the data

Where is the optimal placement for JavaScript code in order to execute a plugin after rendering is complete? <html> <head> <script src='https://cdnjs.cloudflare.com/ajax/libs/es6-promise/3.2.2/es6-promise.min.js'></script ...

Extracting information from ul li div elements and saving it in JSON format

I have been pondering this issue for the past few hours and haven't been able to find a solution. Essentially, I have a list structured like this <ul class="list"> <li class="user"> <div class="name">Name</div> ...

tips for recognizing the selected element

seeking assistance in resolving the issue with the script. once the user selects an item .menu_button, a function called initForm() is invoked. This function is expected to output only console.log(N) but instead, it outputs 3: console.log(1) console.l ...

What is the best way to transfer a variable from a node server to a javascript client when the page is first

My web application is mainly static, but I need to dynamically send the user's username if they are logged in and the room name they specify in the URL to the client-side JavaScript upon page load. Finding a simple solution has been challenging for me ...