How to append a new key to an array of objects using JavaScript

I have encountered a small issue while trying to add the key 'greeting' to an array of objects. Although my code successfully adds the key, it also adds another array at the end when I log the result.

function greetDevelopers(list) {

list.greeting  = list.map(x => x.greeting = `Hi ${x.firstName}, what do 
you like most about ${x.language}?` );


console.log(list);


};

The output I am getting is as follows:

[ { firstName: 'Sofia',
    lastName: 'I.',
    country: 'Argentina',
    continent: 'Americas',
    age: 35,
    language: 'Java',
    greeting: 'Hi Sofia, what do you like most about Java?' },
  { firstName: 'Lukas',
    lastName: 'X.',
    country: 'Croatia',
    continent: 'Europe',
    age: 35,
    language: 'Python',
    greeting: 'Hi Lukas, what do you like most about Python?' },
  { firstName: 'Madison',
    lastName: 'U.',
    country: 'United States',
    continent: 'Americas',
    age: 32,
    language: 'Ruby',
    greeting: 'Hi Madison, what do you like most about Ruby?' },
  greeting: [ 'Hi Sofia, what do you like most about Java?',
    'Hi Lukas, what do you like most about Python?',
    'Hi Madison, what do you like most about Ruby?' ] ]

If anyone has any suggestions on how to ensure that each object retains the 'greeting' key without having it duplicated at the end, I would greatly appreciate it.

Many thanks.

Answer №1

Avoid assigning to list.greeting, as it will assign the result to the array itself, which is not recommended (arrays should only contain elements, not properties). Instead of creating a new array, focus on side-effects by using forEach instead of map. Here's an example where we log the modified array without assigning it to anything:

const input = [ { firstName: 'Sofia',
    lastName: 'I.',
    country: 'Argentina',
    continent: 'Americas',
    age: 35,
    language: 'Java',
  }, { firstName: 'Lukas',
    lastName: 'X.',
    country: 'Croatia',
    continent: 'Europe',
    age: 35,
    language: 'Python',},
  { firstName: 'Madison',
    lastName: 'U.',
    country: 'United States',
    continent: 'Americas',
    age: 32,
    language: 'Ruby',
}];

function greetDevelopers(list) {
  list.forEach((item) => {
    item.greeting = `Hi ${item.firstName}, what do you like most about ${item.language}?`;
  });
  console.log(list);
}
greetDevelopers(input);

Answer №2

To update each object in the array and create a new array, you will need to modify the list.greeting. Instead of just creating a new key, you should replace the existing greeting key in each object.

let inputArray = [{
  firstName: 'Sofia',
  lastName: 'I.',
  country: 'Argentina',
  continent: 'Americas',
  age: 35,
  language: 'Java'
}, {
  firstName: 'Lukas',
  lastName: 'X.',
  country: 'Croatia',
  continent: 'Europe',
  age: 35,
  language: 'Python'
}, {
  firstName: 'Madison',
  lastName: 'U.',
  country: 'United States',
  continent: 'Americas',
  age: 32,
  language: 'Ruby'
}]

function customizeGreetings(array) {

  let newArray = array.map(function(item) {
    item.greeting = `Hi ${item.firstName}, what do you like most about ${item.language}?`
    return item;
  })
 return newArray;
};
console.log(customizeGreetings(inputArray))

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

Guide to integrating react-phone-number-input into material-ui TextField

Would it be possible for me to use a Material UI TextField component as the inputComponent prop for the PhoneInput component from react-phone-number-input? I am facing an issue where I am unable to apply the ref successfully. Even though I can see the Mat ...

Should the ListItem expand and collapse when clicked?

My react/material-ui component has the following structure: export const TodoItem: React.FC<Props> = ( {todo, itemKey}) => { const [dialogState, setDialogState] = React.useState<boolean>(false); const handleClose = () => { setDial ...

Should I release an Aurelia component on NPM?

Our team has developed a compact Aurelia application and now we are looking to seamlessly incorporate it into a larger codebase. One possible scenario is distributing the Aurelia app on NPM to allow other projects to easily integrate our code. What steps ...

Angular 9: Trouble encountered with utilizing custom error handler for error instances

I'm currently working on implementing a custom error handling system in Angular using the ErrorHandler class. This is what my Globalerror service looks like: export class CustomErrors extends Error { button?: any; errObject: any; constructor() ...

Associate a click event to a dropdown menu element to trigger on selection

My issue involves having multiple select elements. When one of them is changed, I am trying to bind a click event only to its next element with the .btn class. Below is the code snippet illustrating my problem: <div class="whole"> <ul> ...

Unveiling ContentVeil.js and the Complications of Forced Synchronous Layouts

My php page is experiencing delays of 3-10 seconds after loading, making it impossible to scroll or close the tab. This issue occurs in both Chrome and IE, with the loading gif continuing to loop. In the Chrome Timeline (link: https://i.sstatic.net/MxuAl. ...

Error: The variable jQuery.atmosphere is not defined in the packed.js file on line 226

Has anyone encountered this specific error before? Error encountered: TypeError: jQuery.atmosphere is undefined packed.js:2261 I have searched for documentation regarding this issue but could not find any. I have ensured that all required dependencies ar ...

The issue arises when using Hive Serde with an Array of Structures where the JSON Array is unable to be converted to a Java Object Array

I have built a table: Add jar /../xlibs/hive-json-serde-0.2.jar; CREATE EXTERNAL TABLE SerdeTest (Unique_ID STRING ,MemberID STRING ,Data ARRAY> ) PARTITIONED BY (Pyear INT, Pmonth INT) ROW FORMAT SERDE "org.apache.hadoop.hive.contrib.serd ...

The state returned by React Redux does not meet the expected results

I recently implemented a like function on the backend using Node and MongoDB. This function successfully returns the post with an updated likes counter, which I tested using Postman. The post object contains properties such as likes, _id, by, createdAt, an ...

Tips for fixing the "Module not found" issue when executing a Node.js application

My Node.js application is encountering an issue when I try to run it using the npm start command. It appears to be failing to locate the entry point file, which results in a "Cannot find module" error. Here's the error message I'm seeing: > P ...

Display visual information without requiring the parameters to be filtered beforehand in vue.js

Upon opening my page, I encountered an issue where the graphics appear blank. This is because I set up the callback for generating graphic data through params request. I wish to first fetch the general data when the page opens, and only load with params w ...

How can I customize a default button in HTML to hide the selected option from the dropdown menu?

Hey there! I'm currently working on a website that needs to be bilingual, with Spanish as the default language. I want to include a dropdown button that allows users to translate the content into English. Here's what I've tried so far: ...

What is the process for inserting text or letters into a checkbox using Material Ui?

I am looking to create circular check boxes with text inside them similar to the image provided. Any help or guidance on achieving this would be greatly appreciated. View the image here ...

Unlocking elements in Vue.js through functions

Looking to dynamically add a class to the label element when focusing on an input element below it. The current HTML and JS code I'm using is as follows: HTML: <label for="formProductId" ref="productIdLabel" class="form-element-title">Product ...

I attempted to utilize body-parser, but it appears that it is not functioning properly

I am having trouble with body parser and express as it is not functioning properly. When I print req.body in the console, it returns an empty object. var express = require('express'); var app = express(); var bodyParser = require('body-pars ...

Position validation in jQuery is crucial for ensuring that form

After attempting to implement the jquery validate plugin by following the example provided at http://docs.jquery.com/Plugins/Validation, I have encountered some challenges in my own code. The issue lies in determining where to call the validation function. ...

What are the steps to enable JavaScript before the next webpage finishes loading?

I am looking to create a loading screen that triggers when a Django form is submitted. Here is an example code snippet: forms.py class ExampleForm(forms.Form): example_field = forms.CharField( widget=forms.TextInput(attrs={'class': ...

Despite working smoothly with an HTML form tag, the "req.file" multer is undefined when it comes to HTTP requests from a script

I have created a basic file uploader using multer in Node.js, which works well when uploading files using an html form like this: <form id="uploadForm" enctype="multipart/form-data" method="post"> <input type="file" name="userFile" /> ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

What methods are available to apply a class to an element in an array when hovering over it?

Is there a way to add a class to an element when hovering over it in an array of elements? ...