The dojo array implemented a new element, pushing out the old one

The JavaScript code below is supposed to populate the array personNames with objects containing names from an array of persons. However, it incorrectly repeats the same name for each object instead of assigning different names:

[{"name":"smith"},{"name":"smith"},{"name":"smith"}]

Instead, it should be generating an array like this:

[{"name":"john"},{"name":"doug"},{"name":"smith"}]

var personNames = []; 
var personName = {}; 

var persons = [{"firstname": "john", "id": "111"}, {"firstname": "doug", "id": "777"}, {"firstname": "smith", "id": "888"}];

if(persons.length > 0){
    array.forEach(persons, function(person){
        personName.name = person.firstname;
        personNames.push(personName);
    });
}

Answer №1

To extract names efficiently, consider using Array.prototype.map:

var persons = [{"firstname": "john", "id": "111"}, {"firstname": "doug", "id": "777"}, {"firstname": "smith", "id": "888"}];

var personNames = persons.map(p => ({ name: p.firstname }));

console.log(personNames);

However, the issue in your code arises from creating an object and repeatedly pushing the same object with altered values to the array.

You might have overlooked something regarding objects and referencing. Here is a corrected version of your implementation:

var persons = [{"firstname": "john", "id": "111"}, {"firstname": "doug", "id": "777"}, {"firstname": "smith", "id": "888"}];

var personNames = [];

persons.forEach(p => personNames.push({ name: p.firstname }));

console.log(personNames);

Additionally, there is no need to verify if there are any items in the persons array.

Answer №2

  iterate through an array of persons and assign their first names to a new object called personName before pushing it into another array called personNames.

personName points to the same object during each iteration due to JavaScript's memory reference behavior, causing updates to reflect everywhere.

To avoid this issue, reset personName for each iteration:

  iterate through an array of persons and assign their first names to a new object called personName before pushing it into another array called personNames.
  

(Should the initial line be changed to

persons.forEach(function(person){
?)

Answer №3

Here is a simple way to utilize the personName variable locally:

var individualNames = [];

var individuals = [{"firstname": "alice", "id": "222"}, {"firstname": "bob", "id": "555"}, {"firstname": "emily", "id": "999"}];

if(individuals.length > 0) {
    individuals.forEach(item => {
      var personName = {};
      personName.title = item.firstname;
      individualNames.push(personName);
    });
}
console.log(individualNames); // [ { title: 'alice' }, { title: 'bob' }, { title: 'emily' } ]

Answer №4

  • $array.forEach() will not work as a function if array is not defined. Make sure to use the correct array name, such as persons.forEach().
  • To avoid accessing the global instance of a variable and instead use it locally, ensure to use personName within the scope where it is declared. View code snippet on JS Bin

   

 var personNames = []; 

var persons = [{"firstname": "john", "id": "111"}, {"firstname": "doug", "id": "777"}, {"firstname": "smith", "id": "888"}];

if(persons.length > 0){
  persons.forEach(function(person){
    //use personName locally
    var personName = {};
    personName.name = person.firstname;

    personNames.push(personName);
  });
}

console.log(personNames);

Answer №5

Give it a shot

var names = []; 

var people = [{"first": "mike", "id": "111"}, {"first": "dave", "id": "777"}, {"first": "jane", "id": "888"}];
for (i = 0; i < people.length; i++) {
   names.push({full: people[i].first});
}

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

When a child component sends props to the parent's useState in React, it may result in the return value being undefined

Is there a way to avoid getting 'undefined' when trying to pass props from a child component to the parent component's useState value? Child component const FilterSelect = props => { const [filterUser, setFilterUser] = useState('a ...

Unable to save data in local storage

I'm enhancing an existing chrome extension while ensuring a consistent style. I am looking to implement a new feature, and I have written a script that saves the user's selection from the popup and sets a new popup based on that choice going forw ...

Validation issue with Reactive Forms not functioning as expected

My latest project involves a user signup component that I created from scratch import { Component } from '@angular/core'; import {UserManagementService} from '../user-management.service'; import {User} from "../user"; import {FormBuild ...

Error rendering {message} object on the Chrome Console

In my ReactJS component, I am utilizing the {message} parameter from props. Check out the code snippet below: import React from "react"; const MyMessage = ({ message }) => { if (message?.attachments?.length > 0) { return ( < ...

Sorting a function with two parameters in descending order is possible even when dealing with an empty array and no initial value for reduction

My npm test is not passing the third out of six tests. I have attempted to sort it using the following code snippet: sumAll.sort(function(min,max)) { return max - min; } However, this approach did not work. I also tried incorporating conditionals in t ...

Is it possible to assign functions to each keystroke that does not correspond to a specific keybinding in Angular?

In Angular, there are events tied to keybindings or actions like (focus), (blur), (keydown), and more. You can bind specific keybinds to certain keys as well, such as (keydown.enter), (keydown.alt), etc. Is there a method to trigger an event only when it ...

Running pug directly from the local node_modules directory

I'm currently attempting to run pug (/jade) from my node_modules directory, however I am unable to locate the executable within the node_modules/.bin folder. I am running MacOS 10.12.5 and installed pug using the "npm install --save pug" command. Is ...

Issue with Bootstrap alignment on the right side

Just finished creating my 'navbar' in bootstrap, but I'm having trouble aligning my unordered list to the right. It's staying in the middle no matter what I try. Can someone please help? Feeling really confused... HTML: <div class= ...

Executing a function by click event using the onclick attribute from a file located in the public directory of my project (Next

I'm new to using Next.js and I have a question about how to utilize onclick to execute a function from an external file located in my public folder. Below is my index.js file: import Head from "next/head" import Script from "next/scrip ...

What is the best way to load a database URL asynchronously and establish a database connection prior to the initialization of an Express

My express.js app is set up to run on AWS lambda, with the database URL stored and encrypted in Amazon KMS. To access the URL, decryption using the AWS KMS service is required. // imports import mongoose from 'mongoose'; import serverless from & ...

There is an issue with the JSON format being received by fetch in JS when using json_encode in php

Recently, I encountered an issue with my JavaScript function that retrieves data from a PHP page. In the JS code block: fetch("print.php) .then(function (r) { return r.json() }) .then(function (values) { ...... ...... ...

Issue encountered during app creation using the command line interface

After successfully installing nodejs and checking the versions of nodejs, npm, and npx, I proceeded to run the command npm install -g create-react-app which executed without any issues. However, when I attempted to create a new React app using create-react ...

Issue with retrieving attributes in the directive

One of the challenges I encountered is incorporating a directive that wraps the jQuery FullCalendar plugin into my project. Here is how I implement the directive: <div sg-calendar format-column-header-month='dddd' format-co ...

Incorporating jQuery Masonry for seamless overlapping effect while implementing infinite scroll

I've developed a script that enables infinite scrolling on my website: $(document).ready(function() { function getLastId() { var lastID = $(".element:last").attr("id"); $.post("2HB.php?action=get&id=" + lastID, ...

During the rendering process, a referenced computed property is not defined on the instance

Description: In my child component, I am working with an array called expenseButton that is passed as props. The array contains objects with values which I need to calculate the sum of using the array.reduce() method. Issue: While I can successfully get ...

I could really use some assistance right now. I'm in the midst of a project where I'm pulling data from web services in JSON format

Dealing with JSON values in a toast messagein my project involves receiving data from the server side, which includes an array with nested arrays in the response. The image shows the "Secondary_number" array with some values that I need to extract and prin ...

Utilizing v-model for dynamic binding within a v-for iteration

I'm currently working on binding v-model dynamically to an object property within an array of objects. I am unsure about how to accomplish this task. The objective is to choose a user using the Select HTML tag and then display the list of that user&ap ...

Vue's beforeRouteEnter hook patiently awaits for the child component to complete its request

My Vue app utilizes beforeRouteEnter to load data and prevent the undesirable "flash of unloaded content." Loading data on some pages is straightforward: async beforeRouteEnter(to, from, next) { const newestPosts = await getNewestPosts(); next(vm ...

Error: AJAX response shows as NaN, indicating that the requested resource was not found

Attempting to create a search engine using AJAX. When typing in the search box, nothing happens. After inspecting the element and opening the console, an error message is displayed: script.js:19 GET http://localhost/var/www/html/pendaftaran-siswa/NaN 404 ( ...

TypeORM Error: Trying to access property 'findOne' of an undefined object

I've been working on implementing TypeORM with Typescript, and I have encountered an issue while trying to create a service that extends the TypeORM repository: export class UserService extends Repository<User> { // ... other service methods ...