Using arrays as properties in literal objects

Attempting to articulate the issue is somewhat challenging, so please refer to the code snippet below.

var test = { 
my_array: [],
my_var: ''
}


var a = Object.create(test);
var b = Object.create(test);


a.my_array.push('aaa');
b.my_array.push('bbb');

a.my_var = 'this is obj A';
b.my_var = 'this is obj B';


document.write(a.my_array[0]); //output: aaa
document.write('<br>');
document.write(b.my_array[0]); //output: aaa
document.write('<br>');
document.write(a.my_var); //output: this is obj A
document.write('<br>');
document.write(b.my_var); //output: this is obj B

What leads to the scenario where both Object b and Object a have the same array value?

Answer №1

Creating two objects that share a common prototype object means that properties on the object prototypes are accessed during property lookups, rather than being duplicated for each instance.

When you set a value to an object property like this:

a.my_var = 'this is obj A';

The property then becomes a unique "own" property of the object, even if it was originally part of the prototype. Changing the value of a prototype property using this assignment method is not possible.

Answer №2

Due to the manner in which objects are created, the property my_array will have the same reference in both objects. Below is a modified version that produces the desired outcome.

var sample = function () {
    return { 
  my_array: [],
  my_var: ''
    }
}

var x = Object.create(sample());
var y = Object.create(sample());

x.my_array.push('aaa');
y.my_array.push('bbb');

x.my_var = 'this is object X';
y.my_var = 'this is object Y';

document.write(x.my_array[0]); //output: aaa
document.write('<br>');
document.write(y.my_array[0]); //output: bbb
document.write('<br>');
document.write(x.my_var); //output: this is obj X
document.write('<br>');
document.write(y.my_var); //output: this is obj Y

Answer №3

Just remember, you're really only constructing one array object in this situation:

my_array: []

Even when you use Object.create to generate a new object from it, that array won't be copied or recreated. Both instances are essentially pointing to the same array object.

Answer №4

Cloning something is pretty straightforward, but what you really need is a deep cloning. When dealing with deep cloning, it requires different techniques because using Object.create() simply copies the property reference if the assigned property is an object or array.

If your goal is to create a deep copy of an object (meaning a thorough copy of all nested properties by traversing the prototype chain), then you should consider taking a different approach. The following example illustrates one possible method. (Source: MDN)

function clone(objectToBeCloned) {
  // Base case.
  if (!(objectToBeCloned instanceof Object)) {
    return objectToBeCloned;
  }

  var objectClone;
  
  // Exclude special objects.
  var Constructor = objectToBeCloned.constructor;
  switch (Constructor) {
    // Handle other special cases here.
    case RegExp:
      objectClone = new Constructor(objectToBeCloned);
      break;
    case Date:
      objectClone = new Constructor(objectToBeCloned.getTime());
      break;
    default:
      objectClone = new Constructor();
  }
  
  // Clone each property.
  for (var prop in objectToBeCloned) {
    objectClone[prop] = clone(objectToBeCloned[prop]);
  }
  
  return objectClone;
}

var test = { 
my_array: [],
my_var: ''
}


var a = clone(test);
var b = clone(test);


a.my_array.push('aaa');
b.my_array.push('bbb');

a.my_var = 'this is obj A';
b.my_var = 'this is obj B';


document.write(a.my_array[0]); //output: aaa
document.write('<br>');
document.write(b.my_array[0]); //output: aaa
document.write('<br>');
document.write(a.my_var); //output: this is obj A
document.write('<br>');
document.write(b.my_var); //output: this is obj B

Answer №5

This specific image provides a clear solution to the question:

https://i.sstatic.net/xyzAb.png

(I simply ran a console.log(a, b))

UPDATE:

An alternative approach to tackle this issue (https://jsfiddle.net/ghijKlmn/):

var example = function() {
  this.data_set = [];
    this.variable_name = '';
} 


var x = new example();
var y = new example();

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

Interacting Between PHP and Javascript

<form action="../"> <select onchange="window.open(this.options[this.selectedIndex].value,'_top')"> <option value="">Choose a zipcode </option> <option value="92507">92507</option> <option value=" ...

Generate a fresh object if the values within the TypeScript object are identical

How can I filter an object to return a new object containing elements with the same values? For example: allValues = {"id1": 3, "id2": 4, "id3": 3} The desired output is: filteredValues = {"id1": 3, "id3": 3} This is because the keys "id1" and "id3" hav ...

Utilizing AngularJS, combining ng-repeat and filter functions that can be triggered directly from the controller

I have a burning question to ask. Here's the HTML code snippet: ng-repeat="item in obj.Items | filter:someFilter" And here's the JS code snippet: $scope.someFilter = function (item) { ... } It all works perfectly fine. However, I am faced wi ...

Having trouble with the JSON response while implementing AngularJS

Recently, I've started working with angularjs and ran into an issue where the data is not loading on the page when pulling JSON from a Joomla component. Strangely enough, everything works perfectly fine when I retrieve the data from a getcustomers.ph ...

Retrieve a comprehensive inventory of all routes within a Vue project and automatically create a sitemap for the website - Vue Project

Imagine I've set up a route like this: import Vue from "vue"; import Router from " vue-router"; import BookRoutes from "./routes/book"; Vue.use(Router) const router = new Router({ routes:[ { path ...

What is the best method for deactivating a button in discord.js after a 5-second delay?

Could use some assistance with discord.js buttons as I am unfamiliar with them. I need to figure out how to disable a button after 5 seconds to prevent spam in my code below: const newEmbed = new Discord.MessageEmbed() .setColor('#2ACAEA') .s ...

Steps to set up datetimepicker with varying date ranges for several input fields

I am having trouble getting a new date range for each text box in my form. It seems to only return the date range from the last textbox, even though I have made the textbox IDs dynamic. I have both start and end dates for each textbox and I have calculated ...

Selecting a pair of radio buttons to toggle the visibility of different div elements using JavaScript

I've been working on two radio button categories that control the visibility of different input fields. I'm making progress, but I'm still struggling to get it to work perfectly. Below are the images for reference: The combination of &apos ...

Several attributes in the JSON object being sent to the MVC controller are missing or have a null

I am facing an issue while passing a JSON object to my MVC controller action via POST. Although the controller action is being called, some elements of the object are showing up as NULL. Specifically, the 'ArticleKey' element is present but the & ...

"Limit the display of the b-form-datepicker to only show the month and

Is there a way to customize the b-form-datepicker in order to only allow selection of the month and year? I've searched through bootstrap-vue but couldn't find an example. ...

Updating the border color in jQuery can be done without affecting the `border-left-color`

I'm working with an element that has the following CSS properties: border: 20px solid; border-color:#4ea88e; border-right-width: 10px; border-left-color: transparent; I need to change the border-color using JavaScript without affecting the border-l ...

Interactive calendar using Php and Javascript/Ajax

Currently, I am working on a PHP calendar and have integrated Javascript/Ajax functionality to enable smooth scrolling between months without the need for page refresh. Interestingly, the calendar displayed as expected before implementing Javascript/Ajax, ...

Error: Attempting to update the value of 'ordersToDisplay' before it has been initialized in a re-render of React. This results in an Uncaught ReferenceError

Trying to dynamically update the document title to include the order number by clicking a button to display different numbers of orders from an array on the screen. The process involves importing a JSON file, filtering it based on user input, calculating ...

Can you confirm if Jquery's $.POST method works asynchronously?

I have been attempting to create a div on my index page that, when clicked, triggers a JavaScript function to send data to a PHP page for computations and MySQL queries. However, despite setting an onclick event handler in my main PHP page, the Chrome deve ...

Is there a way to store the JWT response header retrieved with fetch?

I am currently utilizing React and employing fetch to send a request to the server: fetch("http://localhost:8001/api/login", { method: 'post', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, ...

Show the user's input on the canvas

Currently, my setup consists of 3 elements - a text field and a submit button at the top, with a canvas below them. I am looking for a way to showcase user input on the canvas after they click the submit button. If you have any JavaScript suggestions, I w ...

I am facing an issue where the code in the content script is not getting injected when the URL tab changes. Is there a way to resolve this problem?

Recently, I developed a chrome extension for a website that utilizes ajax calls for page navigation. This caused me to reload the page every time in order for the script to be injected. To circumvent this issue, I implemented the following approach: chrom ...

Retrieving the original state value after updating it with data from local storage

Incorporating the react-timer-hook package into my next.js project has allowed me to showcase a timer, as illustrated in the screenshot below: https://i.stack.imgur.com/ghkEZ.png The challenge now lies in persisting the elapsed time of this timer in loca ...

The type '{ }' does not include the properties 'params', 'isExact', 'path', 'url' from the 'match<Identifiable>' type

Currently, I am utilizing react router and typescript in order to extract the id variable from a route for use in a component. However, typescript is raising an issue: The type '{}' lacks the following properties found in type 'match' ...

Error: Unable to access the 'name' property of an undefined variable

When running the code, I encountered a "TypeError: Cannot read property 'name' of undefined" error, even though when I console.log it, it provides me with the object import React from "react"; class Random extends React.Component { constructo ...