Instructions for removing a single key value pair from every object in an array and transferring it to a designated object within the same array

I need to update an array of objects by adding a key and value (e.g., age:15) to an object with the name email, while removing the age property from other objects in the array.

[
  {
    name: 'test',
    lname: 'last',
    age: 5
  },
  {
    name: 'test1',
    lname: 'last1',
    age: 15
  },
  {
    name: 'email',
    lname: 'last'
  }
]

For example, I want the following output:

[
  {
    name: 'test',
    lname: 'last'
  },
  {
    name: 'test1',
    lname: 'last1'
  },
  {
    name: 'email',
    lname: 'last',
    age: 15
  }
]

Thank you

Answer №1

One approach you can take is to identify the position of the object with a name attribute set to "email". After locating this object, you can introduce a new property labeled age and assign it the desired age value. To complete the process, utilize the filter function to eliminate items that do not have a name of "email" and remove the age property.

var data = [ { name: 'test', lname: 'last', age: 5 }, { name: 'test1', lname: 'last1', age: 15 }, { name: 'email', lname: 'last', }, ]

function myFunction(age) {
  let indexOfEmail = data.findIndex(element => element.name == "email")
  if (indexOfEmail > -1) {
    data[indexOfEmail].age = age
    data.filter(element => element.name !== "email").map(sub => delete sub['age'])
  }
}

myFunction(15)
console.log(data)

Answer №2

If you want to achieve this, you can utilize the map method in the following way:

const info = [
  {
    firstName: 'John',
    lastName: 'Doe',
    age: 25
  },
  {
    firstName: 'Jane',
    lastName: 'Smith',
    age: 35
  },
  {
    firstName: 'Sarah',
    lastName: 'Johnson',
  },
];
const updatedInfo = info.map(({age, ...rest})=> rest.firstName == 'Sarah' ? {...rest, age: 30} : rest)
console.log(updatedInfo);

Answer №3

Here is an example of how you can achieve this:


const items = [
  {
    name: 'test',
    lname: 'last',
    age: 5
  },
  {
    name: 'test1',
    lname: 'last1',
    age: 15
  },
  {
    name: 'email',
    lname: 'last',
  },
];

const newItems = items.filter((item) => {
    if (item.name.includes("email")) {
      return (item.age = 15);
    }
    if (JSON.stringify(items).includes("email")) {
      delete item.age;
    }
    return item;
});

console.log(newItems);

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

Discover properties of a TypeScript class with an existing object

I am currently working on a project where I need to extract all the properties of a class from an object that is created as an instance of this class. My goal is to create a versatile admin page that can be used for any entity that is associated with it. ...

Getting rid of a cookie from the header in Reactjs

Currently, I'm developing an application with Reactjs and utilizing the Next.js framework. To manage user authentication, I've implemented cookies. However, I am facing a challenge when it comes to logging out users and removing the cookie. Could ...

Is there a way in jQuery Validation to apply a rule to the entire form rather than just individual elements within the form?

I am facing an issue with a form where each element has its own custom rules that work perfectly. However, the form cannot be submitted unless values are provided for at least one of its elements. It seems like this is a rule for the entire form rather th ...

How can I pick out paragraphs that don't end with a period and eliminate dashes using jQuery or JavaScript?

Here are the paragraphs I need assistance with: <p>This is the initial paragraph.</p> <p>This is the second one</p> <p>The third paragraph comes next.</p> <p>Last, but not least</p> The second and fourth pa ...

How to eliminate all special characters from a text in Angular

Suppose I receive a string containing special characters that needs to be transformed using filter/pipe, with the additional requirement of capitalizing the first letter of each word. For instance, transforming "@!₪ test stri&!ng₪" into "Test Stri ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...

Tips for organizing nested arrays in PHP based on the sixth index timestamp

I am a newcomer to PHP multi-dimensional arrays and I am seeking a 100% functional solution, please... I have attempted to use the array_multisort and usort functions, but they are not yielding the desired results for me. Frankly, I am unsure of how to ap ...

Generating JSON data with Ruby for a collection of items

I'm a beginner with Ruby. My goal is to generate a JSON file for a set of elements. To achieve this, I am utilizing the each function to fetch the data. The desired structure of the JSON file for a 4 element array is as follows: '{ "desc" ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

Ways to adjust timestamps (DayJs) by increments of 1 minute, 5 minutes, 15 minutes, 30 minutes, and more

Currently, I am exploring time functionality within React Native by utilizing DayJs. I have noticed a slight inconsistency when comparing 2 different points in time to calculate the time difference. Typically, everything works smoothly such as with 10:00 ...

What is the best way to visually refresh a polymer element that displays data from a frequently changing URL?

Hey there! I'm currently facing an issue with displaying a polymer element that contains some important information. This element is supposed to appear when I tap on an icon, but for some reason it doesn't show up even after the data has been loa ...

Learn how to implement Redux login to display the first letter of a user's name and their login name simultaneously

I am implementing a Redux login feature and after successful login, I want to display the first letter of the user's name or email in a span element within the header section. Can anyone provide a solution for this? Below is my Redux login code snippe ...

Array is not being processed accurately

Dealing with a challenge in parsing an array.. Here's a snapshot of the $_GET variable Array ( [perm0] => Array ( [0] => View [1] => Add [2] => Edit [3] => Delete ...

Insert an element into a JSON collection

I am currently working on a JavaScript function that utilizes an ajax call to retrieve data from an API in the form of a JSON array. Here is a snippet of the array structure that I receive: [ { "ErrorType": "Errors", "Explanations": [ { ...

Transformation of Array of Objects to Array of Values using Node.js

I am looking to transform the following: [{ prop1: '100', prop2: false, prop3: null, prop4: 'abc' }, { prop1: '102', prop2: false, prop3: null, prop4: 'def' } ] into this format: [[100,false,null,'abc&ap ...

Adjust grading system based on user interaction with JavaScript

I am currently working on a grading system for a website and I am attempting to modify the interpretation of grades when a column is clicked. Specifically, I am looking to convert Average (%) to Letters to 4.0 Grade Average. To achieve this, I am using Jqu ...

What is the process for moving entered data from one text box to another text box when a checkbox is selected?

I need help with a function that reflects data entered in one text box to another text box when a checkbox is ticked. The checkbox is initially checked and the values should change when it is unchecked and then checked again. Currently, the code is only ou ...

Determine the time difference between two dates, taking into account Daylight Saving Time adjustments

If a start date and number of days are given, I need to calculate the end date by adding the number of days to the start date. This is the code snippet I used: var endDate=new Date(startDate.getTime()+ONE_DAY); Everything was working fine until I notice ...

Discover the steps to capture the ajax initiation and completion events

In my application, I have numerous ajax requests. To display a loading symbol while these requests are in progress, I am utilizing jquery ajaxStart and ajaxStop methods. However, for some reason, they seem to not be functioning as expected. Despite searc ...

Effortlessly automate clicking with JavaScript or HTML - learn how now!

Does anyone know how to automatically click a button on a page when it loads? I attempted using this JavaScript code, but it didn't work. <a href="javascript:Clickheretoprint()" id="print"> <script type="text/javascript"> $(document).rea ...