A guide on updating the values of an array of objects using a different array

As a newcomer to the world of JS, I hope you can bear with me if my question seems complex and possibly repetitive. This issue has been bothering me for quite some time now without finding a satisfactory answer or solution.

I have an array of Objects where I intend to modify certain properties based on another array of equal length. Initially, I assumed this could be easily achieved using a simple for-loop, but to my surprise, all properties ended up with the same value.

Below is the original array of Objects (dattmp) along with the accompanying array (color):

var testdat = {
    Element1: {time: [1586777601886.39, 1586777608597.8, 1586777615309.21]},
    Element2: {time: [1586777603886.39, 1586777638597.8, 1586777315309.21]}
}
var options = {pathOptions: {className: "myclass"}}

var dattmp = [];
for (kys in testdat) {
    var tmp = {
      type: "Feature",
      properties: {
          time: testdat[kys].time,
          path_options: options.pathOptions
      }
    };
    dattmp.push(tmp);
}

var color = ["orange", "blue"];

My objective is to assign distinct colors to each Object within dattmp, such that the first item is orange and the second one is blue.

I attempted both a conventional for-loop and a map, but surprisingly, both instances resulted in all objects having the color blue.

for (var i = 0; i < color.length; i++) {
    dattmp[i].properties.path_options.color = color[i];
}

const newdat = dattmp.map((dt, i)  => {
    dt.properties.path_options.color = color[i];
    return dt;
});

The following method appears to yield the desired outcome, although my IDE indicates numerous issues with the code. Moreover, I am unsure about the usage of the ... notation. Hence, my query is: What would be the correct approach for modifying values individually?

const newdat1 = dattmp.map((dt, i)  => {
    dt = { ...dt, properties: {...dt.properties, path_options: {...dt.properties.path_options, color: color[i]}}};
    return dt;
});

Answer №1

There is an issue where options.pathOptions refers to the same object in both elements of the array. This means that any modification made to it will affect all elements in the array. To avoid this, you can use Object.assign to create a copy of the object.

var testdat = {
  Element1: { time: [1586777601886.39, 1586777608597.8, 1586777615309.21] },
  Element2: { time: [1586777603886.39, 1586777638597.8, 1586777315309.21] },
};
var options = { pathOptions: { className: 'myclass' } };

var dattmp = [];
for (kys in testdat) {
  var tmp = {
    type: 'Feature',
    properties: {
      time: testdat[kys].time,
      path_options: Object.assign({}, options.pathOptions),
    },
  };
  dattmp.push(tmp);
}
var color = ['orange', 'blue'];

for (var i = 0; i < color.length; i++) {
  dattmp[i].properties.path_options.color = color[i];
}
console.log(dattmp);

Answer №2

Take a look at this code snippet:

const dattmp = [];


const color = ["orange", "blue"];

for (let i = 0; i < color.length; i += 1) {
  const obj = {
    properties: {
      path_options: {
        color: color[i],
      },
    },
  };
  dattmp.push(obj);
}

The issue here is attempting to access properties from an empty array.

Update: If you need to retain other properties, you can make use of the following modification:

const newdat1 = dattmp.map((dt, i) => {
  const obj = {
    ...dt,
    properties: {
      ...dt.properties,
      path_options: { ...dt.properties.path_options, color: color[i] },
    },
  };
  return obj;
});

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

"Upon querying with an AJAX POST request, the return value was

I'm encountering an issue where I am attempting to send data from JavaScript to PHP, make a database request, and have the result returned to my JS. However, all I get is "null" as a result. I have verified that my query is correct. Here is the JS cod ...

Is it possible to rewrite this function recursively for a more polished outcome?

The function match assigns a true or false value to an attribute (collapsed) based on the value of a string: function match(children) { var data = $scope.treeData for (var i = 0; i < data.length; i++) { var s = data[i] for (var ...

Instructions on utilizing sockets for transmitting data from javascript to python

How can I establish communication between my Node.js code and Python using sockets? In a nutshell, here is what I am looking for: Node.js: sendInformation(information) Python: receiveInformation() sendNewInformation() Node.js: receiveNewInformation( ...

The XMLHttpRequest() function throws NS_ERROR_FAILURE when sending requests to localhost using either an absolute or relative path

Encountering an error in Firefox 31 ESR: Error: NS_ERROR_FAILURE: Source file: http://localhost/Example/scripts/index.js Line: 18 Similar issue observed on Internet Explorer 11: SCRIPT5022: InvalidStateError The script used for AJAX function call i ...

What is the best way to show a macOS progress pie loading icon alongside files?

While using macOS, a pie loading icon appears next to a file during downloading or transferring. To illustrate, here is an example of a file being downloaded from Chrome: https://i.sstatic.net/8jS4X.png I am interested in implementing a similar feature i ...

What is the best way to apply a hover effect to a specific element?

Within my CSS stylesheet, I've defined the following: li.sort:hover {color: #F00;} All of my list items with the 'sort' class work as intended when the Document Object Model (DOM) is rendered. However, if I dynamically create a brand new ...

Understanding the relationship between csv and json array formats, along with the process of converting them into a json array using Node.js

Greetings! I have been searching for quite some time and have not been able to find the desired result. I am unsure of what a CSV file would look like with the following JSON array: [ { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

The function chrome.notifications.create() is producing incorrect notification IDs upon clicking

Greetings for my first post here. I've been struggling with an issue in a personal project lately. I remember coming across a similar topic on this forum before, but now I can't seem to find it. As far as I recall, the question went unanswered. ...

What is the best way to extract the lowest and highest values from a `rangpicker` when using a price slider?

Can someone provide assistance on retrieving the minimum and maximum value after a mouse-drag operation? Kindly review the code snippet below: <div id="double_number_range" style="margin-top: 13px;"></div> <script type="text/javascrip ...

Unanticipated commitments fulfilled on the spot

While troubleshooting a setup for managing promise concurrency in handling CPU-intensive asynchronous tasks, I encountered perplexing behavior that has left me puzzled. To regulate the flow, my approach was to initially create an array of Promises and the ...

Securing Angular 2+: Safeguarding Server-Side Lazy Loaded Modules

In my Angular 2+ application, users input personal data that is then analyzed in a different section of the app restricted to authorized personnel. The challenge lies in preventing unauthorized individuals from gaining insight into the analysis process. We ...

Activate the drop-down menu in Angular 6 by hovering over it with your mouse

I am just beginning my journey with Angular 6 and Bootstrap. Currently, I am working on a Navigation bar that consists of 3 navigation items. One of the nav items is called "Store", and when a user hovers their mouse over it, I want to display a mega menu ...

Why does IntelliJ IDEA 2016 show an error for using the [ngSwitch] attribute in this Angular2 template?

Every time I run precommit inspections, I receive a barrage of warnings even though everything seems to be functioning properly. The warnings include: Warning:(8, 58) Attribute [ngSwitch] is not allowed here Warning:(9, 42) Attribute [attr.for] is not all ...

Error encountered with the OpenAI API: "The module 'openai' does not have a defined export for 'Configuration'"

I'm encountering an issue while attempting to make an API call to the GPT-3.5 API from OpenAI; all imports from OpenAI are resulting in a 'has no exported member' error. import { Configuration, OpenAIApi } from "openai"; import { a ...

JavaScript offers a variety of options for creating a link-styled button

Is there a distinction between <a href="javascript:;"></a> and <a href="javascript:void(0);"></a> ? I am looking to create a link-styled button that triggers a JavaScript function when clicked, so I implement the following: ...

AngularJS fails to trigger window scroll event

Although I have come across similar inquiries regarding this issue, none of the solutions have proven to be effective for me. Currently, I am working with AngularJS and I am attempting to detect the scroll event. Despite trying numerous variations to capt ...

Changing the URL locale using Next.js router.push is unsuccessful

I am attempting to switch the locale by connecting the onClick event to two separate <div> elements: import { useRouter } from 'next/router' // other codes const router = useRouter() const changeLocale = (locale) => { router.push({ ...

It appears that the font in style.css is not being updated properly and seems to resemble

My issue lies within my CSS code. The text on my website is not displaying correctly and seems to be ignoring the styling that I have applied. Even though I have used similar styling on other buttons which look fine, this specific text element is causing p ...

Is there a way to add text to HTML code using CKEditor?

I incorporate CKEditor into my website. When I click on a specific link, it adds some text to the editor successfully. However, when I switch to the source tab, I am unable to append this text to the existing source code. Can anyone offer guidance on h ...

Guide on formatting a statement and an array onto separate lines within a text file using Python

a = str(mergeSort(lines)) nlines = ['Sorted Numbers',a] with open('SortedNumbers.txt', 'w') as f: f.writelines(nlines) I have an array called mergeSort(lines) which contains a few numbers. The code above successfully crea ...