Adding items to an array causes replication of the content

Encountering an issue while trying to insert an object, populated with values from an array, into another array. The problem arises during the second array.map function. At this point, arrValues ends up containing the current object instead of the one I intended to create in the first place.

Feeling puzzled!

let arrMap = [{
  "field_desc": "Building Name",
  "type": "string"
}]
let objFind = {
  values: [
    ["BUILDING1", "BUILDING2"],
    []
  ]
}


let arrValues = [];
let objValues = {};

objValues.row = 0;
objValues.values = arrMap.map(function(element, index, array) {
  let objFindExcel = objFind.values[0][0];
  element.field_value = objFindExcel;
  return element;
}, []);

arrValues.push(objValues);

objValues = {};

objValues.row = 1;
objValues.values = arrMap.map(function(element, index, array) {
  let objFindExcel = objFind.values[0][1];
  element.field_value = objFindExcel;
  return element;
}, []);

arrValues.push(objValues);
console.log(arrValues);

Expecting the following output:

[{
  "row": 0,
  "values": [{
    "field_desc": "Building Name",
    "type": "string",
    "field_value": "BUILDING1"
  }]
}, {
  "row": 1,
  "values": [{
    "field_desc": "Building Name",
    "type": "string",
    "field_value": "BUILDING2"
  }]
}]

Instead, getting the following outcome:

[{
  "row": 0,
  "values": [{
    "field_desc": "Building Name",
    "type": "string",
    "field_value": "BUILDING2"
  }]
}, {
  "row": 1,
  "values": [{
    "field_desc": "Building Name",
    "type": "string",
    "field_value": "BUILDING2"
  }]
}]

Answer №1

Adjusting the field_value parameter in the elements of the arrMap array will impact all instances tied to the same object.

To resolve this issue, it is recommended to generate a new object for each item in the arrMap array while conducting the mapping operation.

Please see the following code snippet :

let arrMap = [{
  "field_desc": "Building Name",
  "type": "string"
}];
let objFind = {
  values: [
    ["BUILDING1", "BUILDING2"],
    []
  ]
};

let arrValues = [];


function createObject(template, field_value) {
  return {
    field_desc: template.field_desc,
    type: template.type,
    field_value: field_value
  };
}


let objValues = {};
objValues.row = 0;
objValues.values = arrMap.map(function(element, index, array) {
  let objFindExcel = objFind.values[0][0];
  return createObject(element, objFindExcel);
});

arrValues.push(objValues);


objValues = {};
objValues.row = 1;
objValues.values = arrMap.map(function(element, index, array) {
  let objFindExcel = objFind.values[0][1];
  return createObject(element, objFindExcel);
});

arrValues.push(objValues);

console.log(arrValues);

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

User creation causing redirection malfunction

Recently, while working on a website, I encountered an issue with the registration process for users. It was functioning properly when I tested it a few days ago. After making some updates to other aspects of the website such as the login and profile sect ...

Leveraging ES6 with jQuery in Symfony 4

Currently working on a simple app using Symfony 4 and trying to add custom triggers in JavaScript. Having trouble getting my additional code to work as expected, even though it's compiled by Webpack via encore. It seems like my event is not triggering ...

Incorporate JavaScript to include a new class and attribute

Apologies for any language barriers.. I grasp that it involves using addClass and removeClass, but I am uncertain about how to write the terms. I need to ensure that if the screen resolution is less than 768 pixels, then the attributes id="dLabel" type="b ...

"MongoDB's .find function functions properly in the shell environment, but encounters issues when

As a newcomer to Node Express Mongo, I decided to venture into creating my own website after following tutorials. The page I'm working on is a login page. While other people's code has worked for me, my attempt didn't go as planned. Even con ...

Incorporating a setup file into my JavaScript project

In my JavaScript project, I have both frontend and backend codes (NodeJS). Here is the folder structure for my production environment: /prod /server sourceCode1.js sourceCode2.js ... sourceCodeN.js index.js ...

Is it possible for me to input text into html while the page is loading?

Is there a way to preload external files while a web page is loading? I'm looking to incorporate a JavaScript templating engine into my website and prefer to store my templates in separate files. Instead of loading these templates asynchronously, I&ap ...

The inability to read property 0 of undefined persists despite implementing conditional rendering

I'm struggling to understand what mistake I'm making in the current situation: There's an array named arrayOfChildren that gets initialized like this: const [arrayOfChildren, setArrayOfChildren] = React.useState([]) With a handler function ...

Performing matrix manipulations using Mirror.js (Three.js)

I am currently working on creating water effects in three.js and I haven't come across any examples in three.js that incorporate both reflection and refraction. If you know of any examples, please feel free to share the links with me. Currently, I am ...

Exploration of frontend utilization of web API resources

I've come across this issue multiple times. Whenever I modify a resource's result or parameters and search for where it's utilized, I always end up overlooking some hidden part of the application. Do you have any effective techniques to loc ...

Exploring the possibilities with New Relic and React

I am working with a react-router layout which currently contains a string that includes the New Relic javascript snippet. Now, I want to utilize the Browser Agent and set a custom attribute. newrelic.setCustomAttribute(name, value) The global variable n ...

Unable to inject dependencies into Karma testing framework

I am facing the challenge of injecting the $urlRouterProvider into my tests, but I persistently encounter the unknown provider issue. My setup involves ui.router and the testing of directives, requiring access to these providers to prevent test failures... ...

How to create filter components that can be chained together in React?

What is the most efficient way to create reusable, chainable filter components using React? Consider having an array of input data: [ {name: 'Generic t-shirt', size: 'xxl', available: 35}, {name: 'Generic t-shirt', size: &apo ...

discovering the nearest preceding sibling that includes the class .myClass

I have multiple <tr> elements, some of which contain a <td> with the class class="myClass" and some do not. Here is an example of how it may look: <tr> <td class="myClass"></td> <td></td> </tr> <tr> & ...

Update the property of every model within a Backbone collection

Using the pluck method, we can extract an array of attributes from each model in a Backbone collection. var idsInCollection = collection.pluck('id'); // returns ["id1","id2"...] I am curious to know if there is a method that can assign an attri ...

The mongoose.populate() method is failing to display the populated content

// defining user schema const mongoose = require('mongoose'); const {ChatRoom} = require('./chatRoom'); const userSchema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, username:{ type: 'String', unique ...

What could be causing the issue with script.onload not functioning properly in a Chrome userscript?

I am trying to use a userscript to load another script file on a website. However, I am encountering issues with the js.onload event not working as expected. Here is the userscript file: // ==UserScript== // @name Code highlight // @description ...

When attempting to deploy my app, I encountered a CORS error with Nest.js

Currently, I am in the process of building a Nest.js - React.js application. However, I am encountering a cors error despite having cors enabled in my main.ts file of Nest.js. While my application functions smoothly on localhost and an IP address in produ ...

Unable to execute mongoose operation on database collection due to certain restrictions

Currently utilizing Mongoose for communication with MongoDB. Running into issues while attempting to execute certain operations. The database contains a collection named USERS, characterized by the following schema: {username: 'user1', id: 1, l ...

Enhancing the accessibility of Material UI Autocomplete through a Custom ListboxComponent

I have developed a custom ListboxComponent for the MUI Autocomplete component in MUI v4. How can I ensure that it meets the necessary accessibility requirements, such as navigating through options using the arrow keys? <Autocomplete ListboxComponent ...

Locate the two absent numbers in a set of whole numbers containing two omissions

Can you explain the process for this task? The values are disordered but fall within the range of [1..n]. For example, consider the array [3,1,2,5,7,8]. The correct answer is 4, 6. I came across a similar solution in another post, however I am struggling ...