Is there a way to change the name within an array of objects?

let myArray = [
  { age: 21 },
  { name: 'Sara' },
  { test01: 'bla' },
  { test02: 'bla' }
];

I have an array of objects and I need to update only the "name" property. How should I go about it?

This is the desired outcome:

let myArray = [
  { test: "Jhon" },
  { name: "Alex" },
  { test01: "Domnic" },
  { test02: "Bravo" }
];

Answer №1

To update only the elements with the name parameter, you can follow this method:

let myArray = [
  { test: 'Jhon' },
  { name: 'Sara' },
  { test01: 'Domnic' },
  { test02: 'Bravo' }
];
console.log("Before");
console.log(myArray);
myArray = myArray.map(r => {
  if (r.hasOwnProperty("name")) {
    return {name: "Praveen"};
  }
  return r;
});
console.log("After");
console.log(myArray);

The outcome of the updated array depends on your desired result. For example, to change the name from Jhon to Praveen for the first user:

let myArray = [
  { test: 'Jhon' },
  { name: 'Sara' },
  { test01: 'Domnic' },
  { test02: 'Bravo' }
];
console.log("Before");
console.log(myArray);
myArray[0].test = "Praveen";
console.log("After");
console.log(myArray);

If you wish to change the name of every element in the array without altering the index:

let myArray = [
  { test: 'Jhon' },
  { name: 'Sara' },
  { test01: 'Domnic' },
  { test02: 'Bravo' }
];
console.log("Before");
console.log(myArray);
myArray[1].name = "Praveen";
console.log("After");
console.log(myArray);

Answer №2

To update the name of a specific object in an array, you can utilize the array index to target the object and modify its value accordingly.

let myArray = [
      { test: 'John' },
      { name: 'Sarah' },
      { test01: 'Dominic' },
      { test02: 'Bravo' }
    ];

myArray[1].name = "Jane";

console.log(myArray);

When using myArray[1], you will access the second object within the array, where the key "name" has the initial value of Sarah.

{ name: 'Sarah' }

Answer №3

Another way to accomplish this is by utilizing a for-of loop. The advantage of using this method is that it will simply update the value of the name property without discarding the previous object.

for(let obj of myArray) { 
    if ('name' in obj) { // An alternate approach to verifying property existence
        obj.name = 'Rohan';
    }
}

Answer №4

Give this a try, it should work for your situation:

 let myArray = [
    { test: 'Jhon' },
    { name: 'Sara' },
    { test01: 'Domnic' },
    { test02: 'Bravo' }
    ];


   updatedArr= myArray.map(m=>{
      let key=Object.keys(m);
      if(key[0]==="name")
      {return {name: "new Name"}}
      return m
    })
    console.log(updatedArr)

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

Switching the checkbox value upon clicking a div element

One challenge I am facing is with a checkbox that saves its value and title in the local storage when clicked. This checkbox is located within a div, and I want the checkbox value to change whenever any part of the div is clicked. Despite my efforts, I hav ...

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

How can UI tests be run in headless mode in Selenium 4 and above?

Selenium recently announced the release of Selenium 4, and they have also mentioned that there will be no support for PhantomJS from Selenium 4 onwards. Does this mean that Selenium no longer supports headless automation, or is there a different method t ...

Tips for styling an array of objects using mapping techniques

I have an array of messages and I am currently using the map() function. Each message in the array has two keys - one for the author and another for the message content. What I want to achieve is to change the styles of the div tag when displaying the last ...

Refine JSON data by selecting only distinct key/value pairs

My JSON object has the following structure: var theSchools = { Bradley University: "bru", Knox College: "knox", Southern Illinois University Edwardsville: "siue",… } I am trying to find a way to retrieve the school name (key) based on the schoo ...

Issue with the close button on ngb-alert not functioning properly

As I develop my website, I have incorporated an ngb-alert component to display an alert message to users upon login. While the alert itself is functioning properly, I have encountered an issue with the close button being misaligned, and I am struggling to ...

Creating Layouts with Bootstrap 3

I'm exploring the codepen below in an attempt to mimic the appearance of the image provided consistently across all screen sizes. However, there are two issues that I am encountering - firstly, the green numbers on the first line which represent the d ...

What is the method for identifying modules that rely on a specific module?

Is it possible to view all dependencies modules of a specific module, similar to this: npm-remote-ls <module-name> But how can we see the modules that depend on a particular module? Any help would be appreciated. Thank you. ...

I'm encountering a type error every time I attempt to render an EJS page. Could someone please take a look and help me troubleshoot?

Below is the index.js code: CODE HERE const express = require('express'); const app = express(); const path = require('path'); app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded app.use(ex ...

Adding items following a series of impacts

Is there a way to modify this code so that instead of the block being added the first time it is hit, it gets appended and then removed after being hit five times? I've been experiencing issues with portions of my game disappearing every time I make s ...

Confirm whether the Iterator type is the same as the AsyncIterator type

Is there a clever JavaScript technique to differentiate between Iterator and AsyncIterator without initiating the iteration process? I'm attempting to create a type checker like this: function isAsyncIterator<T>(i: Iterator<T> | AsyncIter ...

Transfer information via query or retrieve from storage in Vue

When considering sending a data variable to another component, is it more efficient to send it via query using a router or save the data in-store? Which method would be more optimal? router.replace({ name: 'routerName', query: { param ...

The stylesheet is linked, but no changes are taking effect

I've linked my template.php to style.css, and when I make changes in template.php, they show up fine. However, if I make changes in the stylesheet, nothing happens. What should I do? My website is not live; I'm working on it using a WAMP server. ...

Is it possible to capture a screen recording in Selenium using JavaScript?

While my tests are running, I am looking for a way to record my screen. I came across a post about screen recording using Java at . However, the code provided is in Java and I require something in JavaScript. Is it possible to record the screen using Jav ...

Selenium, scrolling through web pages

I have been attempting to scroll through a webpage using Selenium at "https://jobsearch.az/vacancies". However, when you open the page and click on a job vacancy, there are two side-by-side pages that need to be scrolled. The challenge is to scroll the one ...

Transferring binary data from C# to Node.js for deserialization

I am facing a challenge where I have a byte array created in C# from an object type, which is then sent over the socket protocol to a Node.js app. However, I am unable to deserialize the data into a readable object. Can anyone suggest a way to decode this ...

What is the best way to switch between components in vue.js?

I have created a Dashboard.vue component consisting of two child components: DisplayBooks.vue and sortBooksLowtoHigh.vue. Initially, the sortBooksLowToHigh component is hidden while the displayBooks component is visible by default. The requirement is that ...

Explore ways to incorporate special symbols in a jQuery array

I'm looking to include special characters in a jQuery array. I'm not quite sure how to do this. Currently, my code is: $scope.categories = ['Red', 'White', 'Rose', 'Sparkling']; and I would like it to be: ...

Is utilizing getStaticProps the best approach for handling offline data in Next.js?

My current project in Next.js involves offline static data for the webpage content. I am using an array to store the data for later mapping. Do you recommend using getStaticProps in this scenario? For example, here is a snippet of my code: import { data } ...

The validation using regex is unsuccessful when the 6th character is entered

My attempt at validating URLs is encountering a problem. It consistently fails after the input reaches the 6th letter. Even when I type in "www.google.com," which is listed as a valid URL, it still fails to pass the validation. For example: w ww www ww ...