Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a javascript object with and object inside an array

I am just curious about this.

Let's say I have an array of objects and I create 1 object, lets name the array of objects items and the object item.

I want to get a particular item in my array of items by using the following code:

//gets an item base on ID
function get_item(td){
    var item = undefined;
    $.each(items, function(i, val) {
        if(val.item_id == td){
            item = val;
        }   
    });
    return item;
}

The get_item() basically gets an object matched with the supplied id.

So my question is this. What if I changed the properties of item will it also changed the properties of an object associated with it within the array?

Thank you very much!

like image 445
iamjc015 Avatar asked Jun 01 '15 04:06

iamjc015


People also ask

How do you assign an object to an array of objects?

assign() method to convert an array to an object, e.g. const obj = Object. assign({}, arr) . The Object. assign method takes a target and source objects as parameters, applies the properties from the sources to the target and returns the result.

Can an array contain both numbers and objects at the same time in JavaScript?

JavaScript arrays can indeed contain any and all types of data. An array may contain other objects (including other arrays) as well as any number of primitive values like strings, null , and undefined . When you place an object inside of another object, it's called a nested object.

Can you put an object inside an array?

There are 3 popular methods which can be used to insert or add an object to an array. The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method.

Can we add object inside object in JavaScript?

object1. content1 = object2;//this is the code you are looking for console. log(object2); You are done!


1 Answers

What if I changed the properties of item will it also changed the properties of an object associated with it within the array?

Yes.

Objects are not copied. Instead, references to the objects are passed around. Simplest example:

var a = [];
var b = a;
b.push(1);
console.log(a); // logs [1]

Many object-oriented programming languages work like this.

like image 140
Felix Kling Avatar answered Oct 29 '22 21:10

Felix Kling