Ways to set values for an array of objects containing identical key names

 let people = [ { firstName: 'Ben' }, {firstName : 'Bob' } ];
 let location =  { city: 'Dublin' , Country: 'Ireland' } ;
 let result = [];
 let tempObj = {};
 for(let person of people){
   tempObj = Object.assign({}, location);
   tempObj['fname'] = person.firstName;
   result.push(tempObj);
 }

expected output :

[ {fname:'Ben', city: 'Dublin' , Country: 'Ireland'}, {fname:'Bob',city: 
'Dublin' , Country: 'Ireland'}]

what I'm getting is:

[ {fname:'Ben', city: 'Dublin' , Country: 'Ireland'}, {fname:'Ben', city: 'Dublin' , Country: 'Ireland'}}]

What am I doing wrong here?

Answer №1

By creating a new object inside the for loop each time, you can avoid pushing the same reference into the array multiple times. This way, each object in the array will have its own unique reference.


let personNames = [{ firstName: 'Alice' }, {firstName : 'Alex' }];
let nameList = [];

for(let name of personNames){
  let nameObj = {};
  nameObj['f_name'] = name.firstName;
  nameList.push(nameObj);
}

Answer №2

To accomplish this task, you can utilize the Array.map method from ES6.

const people = [{
  name: 'Alice',
}, {
  name : 'Alex',
}];

const newNameList = people.map(person => ({
  n_name: person.name,
}));
 
console.log(newNameList);


In the code snippet above, we are iterating over each element in the array 'people' and creating a new object for each element with a key called 'n_name'.

Answer №3

The for loop needs to include the nameObj variable

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

The onclick attribute on a button in HTML is not functioning properly following the inclusion of an Ajax load

I am facing an issue with a button that is being dynamically loaded from PHP code using Ajax. The button has an onclick attribute that calls a function named viewImage. The Ajax request is triggered every 5 seconds inside the loadImages function. Snippet ...

Optimizing React components by efficiently updating props without triggering unnecessary renders

As I delve into learning React, I've encountered a challenge with using a component to display details of a selected item in a table. The issue arises when clicking "Next" on the paginated table, causing the state to update and re-render the component ...

Form fields in Bootstrap 4 will consistently expand downward in the select dropdown menu

When using bootstrap 4, I want my field to always expand downwards and never upwards, even when half the screen is taken up by the form's select element. How can I achieve this effect? I have tried using data-dropup-auto="false" but it didn't wo ...

I keep encountering the following issue: "It seems that the file requested at /images/crown.png is not recognized as a valid image, as it was received as text/html; charset=utf-8."

I encountered an issue while utilizing Next.js. Here is the code snippet where the error occurred: import React from "react"; import { Container, Col, Row } from "react-bootstrap"; import Image from "next/image"; export defaul ...

Discovering the most recent Node.js version: A step-by-step guide

Is it possible to check the latest available Nodejs version using npm? While node -v allows us to see the current version, I am curious if there is a way to access the most recent version through JavaScript. For example, process.version can be used to vi ...

Is there a way to dynamically update the text in an HTML element with a randomly generated value using JavaScript?

Currently, I am working on a coding project where I am attempting to create a flip box that reveals the name of a superhero from an array when clicked by a user. The code pen link provided showcases my progress so far: https://codepen.io/zakero/pen/YmGmwK. ...

"The Django querydict receives extra empty brackets '[]' when using jQuery ajax post to append items to a list in the app

Currently, I am tackling a project in Django where I am utilizing Jquery's ajax method to send a post request. The csrftoken is obtained from the browser's cookie using JavaScript. $.ajax({ type : 'POST', beforeSend: funct ...

Asynchronous loading of HTML templates using JQuery/JavaScript

Currently, I am in the process of creating a webpage that includes code snippets loaded from txt files. The paths and locations of these txt files are stored in a json file. First, the json file is loaded in, and it looks something like this: [ {"root":"n ...

The error message "Can't resolve all parameters for CustomerService" is preventing Angular from injecting HttpClient

I have a customerService where I am attempting to inject httpClient. The error occurs on the line where I commented //error happens on this line. Everything works fine until I try to inject httpClient into my service. The error message is: `compiler.js: ...

Tips on dividing the information in AngularJS

Sample JS code: $scope.data={"0.19", "C:0.13", "C:0.196|D:0.23"} .filter('formatData', function () { return function (input) { if (input.indexOf(":") != -1) { var output = input .split ...

Is it possible for me to convert my .ejs file to .html in order to make it compatible with Node.js and Express?

I have an index.html file and I wanted to link it to a twitter.ejs page. Unfortunately, my attempts were unsuccessful, and now I am considering changing the extension from ejs to html. However, this approach did not work either. Do .ejs files only work wit ...

Encountering issue: Unrecognized parameter "id" in the "user" field of type "Query" [GraphQL, Relay, React]

We are currently setting up a query in relay. Our user database is structured like this: function User(id, name, description) { this.id = id.toString() this.name = name this.description = description } var users = [new User(1, 'abc', &a ...

Ionic 5 page div within ion-contents element is experiencing scrolling issues on iPhone devices

My application features a div element containing an ion-slides component. The ion-slides component houses several ion-slide elements that slide horizontally. Here is the relevant code snippet: <ion-content [scrollEvents]="true"> <div ...

What is the best way to showcase a set of paired arrays as key-value pairs?

Currently, I am developing a client in React that is responsible for receiving streaming data that represents objects from the back end. The client's task is to parse this data and dynamically construct the object as a JavaScript data structure, typic ...

Error: Cannot use Object.fromEntries as a function

I encountered an issue with some older iPhones, specifically iPhone 7 and iPhone 10. https://i.sstatic.net/gX32N.png I have been unsuccessful in finding a solution to this problem. The libraries I am utilizing "@chakra-ui/react": "^1.4.1 ...

React.js - Add a new row div when reaching a limit of X items to keep the layout

Currently in the process of learning React.js. Here is the code snippet I am working with: const items = Object .keys(this.state.items) .map(key => <Item key={key} details={this.state.items[key]} />) ; return ( <div className ...

Ways to modify, delete, or insert data elements within a collection of values using React

I'm currently working on implementing a dropdown menu for departments within a location edit form. I'm wondering if there's a way to update or create new elements in the list of values. The API I'm using only sends specific data elemen ...

What is the method to determine the overall size of a webpage using the Google PageSpeed API?

"analytics": { "cssResponseBytes": "333 kB", "htmlResponseBytes": "269 kB", "imageResponseBytes": "3.35 MB", "javascriptResponseBytes": "2.29 MB", "numberCssResources": 2, "numberHosts": 80, "numberJsResources": 72, "numberR ...

What is the most reliable method for converting a 32-bit unsigned integer to a big endian byte array?

Looking for a simple and reliable method to convert an unsigned integer into a four-byte-array in big endian format, with padding if necessary? Take a look at this example: Input value: 714 Output: Resulting byte array [ 0xca, 0x02, 0x00, 0x00 ]; By the ...

Using an array in jade rendering

I'm currently working on a node.js server using express and I'm facing an issue with passing an array to jade rendering. Here's the code snippet from my node.js file: router.get('/render', function(req, res) { var t; var ...