Array of objects, with individual properties in javascript - javascript

I am trying to build an array of objects in javascript.
Somehow I have not found the answer I am looking for anywhere. Yes I did search questions.
So a traditional object has properties obviously such as:
item being the object
item = new Object();
with properties and methods
item.name = "sword"; // "sword" being the string name of the object
item.buy = buy; //buy being a function to add said item
that's just great and I get that.
I get arrays too.
My question is, if I want say 20 of those objects, how could i make them in an array instead of making many objects
example, I know I can do this.
item1 = new Object();
item1.name = "sword";
item1.buy = buy;
item2 = new Object();
item2.name = "shield";
item2.buy = buy;
However, I would like to do something like this
item = new Array();
item[0].name = "sword";
item[0].buy = buy;
item[1].name = "shield";
item[1].buy = buy;
Maybe it's obvious, but I'm not getting what's wrong here.
When i attempt to call
item[0].buy();
I encounter the error "Uncaught TypeError: Object 0 has no method 'buy' " and item[0].name is undefined.
What am I doing wrong and how do I go about this?

My guess is that what you want is an array of objects:
var item = new Array();
item[0] = {};
item[0].name = "sword";
item[0].buy = function() { return this.name };
item[0].buy();
// -> "sword"

// create a new array
var items = [];
// You can push objects onto the array as literals like this
items.push({
name: "sword",
buy: buy
});
// Or you can create the new object as you're doing currently
var item = new Object();
item.name = "shield";
item.buy = buy;
// And push it onto the array as before
items.push(item);
// Now you can access each object by it's index in the array
items[0].buy();
console.log(items[1].name); // "shield"

You can use literals like this:
var items = [{
name: '1',
buy: buy
}, {
name: '2',
buy: buy
}, {
name: '3',
buy: buy
}];
But I would consider using prototypes since buy is a shared method:
function Item(name) {
this.name = name;
}
Item.prototype.buy = function() {
...
};
var items = [
new Item('1'),
new Item('2'),
new Item('3')
];
items[1].buy();

Can simplify the syntax down to:
var arr=[
{name:'foo',age:49},
{name:'GG', age:12},
{name:'MMMM', age:16}
];
All depends what your overall goal is.
Using var xyz={} is same as writing out new Object() simlarly for [] to start a new array

You can create a function called Item that will return an object with the name property, then use prototype to attach a method to it. Although JavaScript does not have classes, this will behave similar to it.
function Item(name) {
this.name = name
}
Item.prototype.buy = function() {
// your code to buy an item
// you can access your item's name property here by using this.name
alert("You bought the item " + this.name)
}
Then, you can instantiate this function and add the returned objects to an array:
var items = []
items.push(new Item('sword'))
items.push(new Item('shield'))
items[0].buy() // will buy the item "sword"
items[1].buy() // will but the item "shield"

looks as though you didn't add the items to your array via items.push(item1)
item1 = {};
item2 = {};
item1.name = "a";
item2.name = "b";
var buy = function() { console.log('buying... '+this.name); };
item1.buy = buy;
item2.buy = buy;
var items = [];
items.push(item1);
items.push(item2);
items[0].buy();

Because, you didn't create any object at the 0 index of your array and buy should be a function
item = new Array();
// create an object at 0/first index of array which is equivalent of new Object
item[0] = {};
// create property 'name' and assign value ("sword") to it
item[0].name = "sword";
// create another property and assign a function as it's value
// so buy is a method of the first object that is in in the item array
item[0].buy = function(){
return 'buy called';
};
// call 'buy' method from the first object of item array
console.log(item[0].buy());

Related

How is it possible to add an array argument to a constructor for an object, thus to give each object its own array?

Is it possible to have a object constructor where each objects has its own array?
I am have trouble figuring out the syntax if so.
Right now I am creating objects and a separate array to co-aside the object(waiters) array.
function Waiter (name, orders[]) {
this.name = name;
this.orders = orders;
}
// Constructor for waiter object
function Waiter (name) {
this.name = name;
}
// Waiter objects
var waiterOne = new Waiter('Timo');
var waiterTwo = new Waiter('Lucian');
var waiterThree = new Waiter('Arpi');
// Array to store waiter object
var waiters = [
waiterOne,
waiterTwo,
waiterThree
];
// Count so that the same number of arrays are create as waiters
var countWaiterOrders = waiters.length;
// Creating a order array for each waiter object
for(var i = 0; i <= countWaiterOrders; i++){
var order = [i];
}
Getting error:
Uncaught SyntaxError: Unexpected token [
Is the error message I get when trying to pass an array to the constructor.
The desired result would just be that each Waiter object has its own array for orders.
ex:
console.log(waiters[0]);
Waiter {name: "Timo", orders: []}
Silly question I was just a bit stuck for a while you assign the value to an empty array not the argument.
//Waiter constructor
function Waiter (name, order) {
this.name = name;
this.order = [];
}
Please correct me if I'm missing something, but it seems that you could just use something like this:
class Waiter {
constructor(name) {
this.name = name
this.orders = []
}
}
What you are doing here is creating a class Waiter to which you pass a name as variable.
You can create a Waiter like so: var waiterOne = new Waiter('Tim').
This would then allow you to use waiterOne.name or waiterOne.orders, as the array of orders is created in the constructor of the class.
If you wanted to store all your waiters in the array, the good method may be to create a collection class called Waiters - This could be useful if you wanted to do some operations on the whole collection of your Waiters.

Adding elements to object

I need to populate a json file, now I have something like this:
{"element":{"id":10,"quantity":1}}
And I need to add another "element". My first step is putting that json in a Object type using cart = JSON.parse, now I need to add the new element.
I supposed I must use cart.push to add another element, I tried this:
var element = {};
element.push({ id: id, quantity: quantity });
cart.push(element);
But I got error "Object has no method push" when I try to do element.push, and I think I'm doing something VERY wrong because I'm not telling the "element" anywhere.
How can I do that?
Edit: sorry to all I had a LOT of confusion in my head.
I thought I can get only object type when taking data from JSON.parse, but I get what I put in the JSON in the first place.
Putting array instead of object solved my problem, I used lots of suggestions got here too, thank you all!
Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
JSON.stringify() was mentioned as a concern in the comment:
>> JSON.stringify([{a: 1}, {a: 2}])
"[{"a":1},{"a":2}]"
The line of code below defines element as a plain object.
let element = {}
This type of JavaScript object with {} around it has no push() method. To add new items to an object like this, use this syntax:
element[yourKey] = yourValue
To put it all together, see the example below:
let element = {} // make an empty object
/* --- Add Things To The Object --- */
element['active'] = true // 'active' is the key, and 'true' is the value
console.log(element) // Expected result -> {type: true}
element['state'] = 'slow' // 'state' is the key and 'slow' is the value
console.log(element) // Expected result -> {type: true, state: 'slow'}
On the other hand, if you defined the object as an array (i.e. using [] instead of {}), then you can add new elements using the push() method.
To append to an object use Object.assign
var ElementList ={}
function addElement (ElementList, element) {
let newList = Object.assign(ElementList, element)
return newList
}
console.log(ElementList)
Output:
{"element":{"id":10,"quantity":1},"element":{"id":11,"quantity":2}}
If the cart has to be stored as an object and not array (Although I would recommend storing as an []) you can always change the structure to use the ID as the key:
var element = { quantity: quantity };
cart[id] = element;
This allows you to add multiple items to the cart like so:
cart["1"] = { quantity: 5};
cart["2"] = { quantity: 10};
// Cart is now:
// { "1": { quantity: 5 }, "2": { quantity: 10 } }
Adding new key/pair elements into the original object:
const obj = { a:1, b:2 }
const add = { c:3, d:4, e: ['x','y','z'] }
Object.entries(add).forEach(([key,value]) => { obj[key] = value })
obj new value:
{a: 1, b: 2, c: 3, d: 4, e: ['x', 'y', 'z'] }
I was reading something related to this try if it is useful.
1.Define a push function inside a object.
let obj={push:function push(element){ [].push.call(this,element)}};
Now you can push elements like an array
obj.push(1)
obj.push({a:1})
obj.push([1,2,3])
This will produce this object
obj={
0: 1
1: {a: 1}
2: (3) [1, 2, 3]
length: 3
}
Notice the elements are added with indexes and also see that there is a new length property added to the object.This will be useful to find the length of the object too.This works because of the generic nature of push() function
you should write var element = [];
in javascript {} is an empty object and [] is an empty array.
cart.push({"element":{ id: id, quantity: quantity }});
function addValueInObject(object, key, value) {
var res = {};
var textObject = JSON.stringify(object);
if (textObject === '{}') {
res = JSON.parse('{"' + key + '":"' + value + '"}');
} else {
res = JSON.parse('{' + textObject.substring(1, textObject.length - 1) + ',"' + key + '":"' + value + '"}');
}
return res;
}
this code is worked.
Try this:
var data = [{field:"Data",type:"date"}, {field:"Numero",type:"number"}];
var columns = {};
var index = 0;
$.each(data, function() {
columns[index] = {
field : this.field,
type : this.type
};
index++;
});
console.log(columns);
If anyone comes looking to create a similar JSON, just without using cart as an array, here goes:
I have an array of objects myArr as:
var myArr = [{resourceType:"myRT",
id: 1,
value:"ha"},
{resourceType:"myRT",
id: 2,
value:"he"},
{resourceType:"myRT",
id: 3,
value:"Li"}];
and I will attempt to create a JSON with the following structure:
{
"1":{"resourceType":"myRT","id":"1","value":"ha"},
"2":{"resourceType":"myRT","id":"2","value":"he"},
"3":{"resourceType":"myRT","id":"3","value":"Li"}
}
you can simply do-
var cart = {};
myArr.map(function(myObj){
cart[myObj.id]= myObj;
});
function addValueInObject(value, object, key) {
var addMoreOptions = eval('{"' + key + '":' + value + '}');
if(addMoreOptions != null) {
var textObject = JSON.stringify(object);
textObject = textObject.substring(1,textObject.length-1);
var AddElement = JSON.stringify(addMoreOptions);
object = eval('{' + textObject +','+ AddElement.substring(1,AddElement.length-1) + '}');
}
return object;
}
addValueInObject('sdfasfas', yourObject, 'keyname');
OR:
var obj = {'key':'value'};
obj.key2 = 'value2';
For anyone still looking for a solution, I think that the objects should have been stored in an array like...
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
Then when you want to use an element as an object you can do this...
var element = cart.find(function (el) { return el.id === "id_that_we_want";});
Put a variable at "id_that_we_want" and give it the id of the element that we want from our array. An "elemnt" object is returned. Of course we dont have to us id to find the object. We could use any other property to do the find.
My proposition is to use different data structure that proposed already in other answers - it allows you to make push on card.elements and allow to expand card properties:
let card = {
elements: [
{"id":10,"quantity":1}
],
//other card fields like 'owner' or something...
}
card.elements.push({"id":22,"quantity":3})
console.log(card);
push is an method of arrays , so for object you can get the index of last element ,and you can probably do the same job as push for object as below
var lastIndex = Object.keys(element)[Object.keys(element).length-1];
then add object to the new index of element
element[parseInt(lastIndex) +1] = { id: id, quantity: quantity };
if you not design to do loop with in JS e.g. pass to PHP to do loop for you
let decision = {}
decision[code+'#'+row] = event.target.value
this concept may help a bit
This is an old question, anyway today the best practice is by using Object.defineProperty
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false
});
object1.property1 = 77;
// throws an error in strict mode
console.log(object1.property1);
// expected output: 42
In case anyone else needs this, I finally found a good way to add objects or arrays of objects:
var myobj = {}
// These two options only work for single-valued keys, not arrays or objects
myobj["a"] = 1
myobj.b = 2
// This one works for everyting:
Object.assign(myobj, {"key": "value"}); // single-value
// Add object
Object.assign(myobj, {"subobj":
{
"c": 3
}
});
// Add array of objects
Object.assign(myobj, {"subarr":
[
{
"d": 4,
},
{
"e": 5
}
]
});
var newObject = {element:{"id":10,"quantity":1}};
console.log(newObject);

JavaScript arrays braces vs brackets

What is the difference between each of the following array definitions.
var myArray = [];
var myArray = {};
var myArray = new Array();
The first and third are equivalent and create a new array. The second creates a new empty object, not an array.
var myArray = []; //create a new array
var myArray = {}; //creates **a new empty object**
var myArray = new Array(); //create a new array
var myObject = {}; is equivalent to var myObject = new Object();
So, the second example is not an Array but a general Object.
This can get confusing as Array is a class and Object is a class - more precisely Array is a sub-class of Object. So, by and large, Object semantics are applicable to an Array:
var o = [];
o.push('element1');
o.push('element2');
o['property1'] = 'property value'; // define a custom property.
console.log(o.property1);
console.log(o.length); // Outputs '2' as we've only push()'ed two elements onto the Array

What does [] mean in JavaScript?

In the following javascript code there is [] being assigned as the value of a variable, what does it mean?
var openTollDebug = [];
it is an array literal. It is not quite the same as declaring new Array() - the Array object can be overwritten in JavaScript, but the array literal can't. Here's an example to demonstrate
// let's overwrite the Array object
Array = function(id) {
this.id = id;
}
var a = new Array(1);
var b = [];
console.log(a.hasOwnProperty("id")); // true
console.log(b.hasOwnProperty("id")); // false
console.log(a.push); // false, push doesn't exist on a
console.log(b.push); // true, but it does on b
b.push(2);
console.log(b); // outputs [2]
It means an array.
var openTollDebug = [];
declares the openTollDebug variable and initializes it to an empty array. To put elements into the array you could do the following:
var stringArray = ['element1', 'element2', 'element3'];
alert(stringArray[1]); // displays 'element2'
var numberArray = [1, 2, 3, 4];
alert(numberArray[2]); // displays 3
var objectArray = [{ name: 'john' }, { name: 'peter' }, { name: 'tom' }];
alert(objectArray[1].name); // displays 'peter'
It's an empty array, and is equal to
var openTollDebug = new Array();
It is shorthand for empty array. Same as new Array().
Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary.
It creates an empty array.
This is a good way to have a non-null object.
In JavaScript, it is then very easy to add functions and properties to that object. For example:
openTollDebug.title = 'hello world';
openTollDebug.show = function(){alert('Debug');};
As an array, you can add items:
openTollDebug.push('added item');
openTollDebug[3] = 'just add anywhere';
Many languages have constructs for literals. The [] is an Array literal.
var openTollDebug = [];
is the same as
var openTollDebug = new Array();
Just know that using [] preferred for performance reasons.
There are other literals like Object literals
var MyObject = {
name:'default',
age:22,
hobbies:["golf","video games","otherstuff"]
}
Notice the array literal with data. The [] creates an empty array.
Try to use literals due to performance. You dont write
var obj = new Object({name: 'John'})
You just write
var obj = {name: 'John'}
You also dont write
button.onclick = new Function("alert('Clicked!')");
You write
button.onclick = function () { alert('Clicked') }
And here's a link to a nice blog post about it
var b = [] //it is an array literal.

method Array.push() javascript

I need to add a new item to array or change the item by id, but When I call the method push, it just creates a new item with a key 0,1,2...
I wrote this array
var finalArray = [];
button.addEventListener('click', function(){
id=123;
writeArray(id, "Jason");
//When I click the button, array always create a new item instead of change the item by id (123).
});
function writeArray(id, name){
var array = {
[id]:{
name: name
}
};
finalArray.push(array);
}
In result, array always creates a new item which is showing below. But I need to change the item by id.
0:{
123: {
name: "Chinga"
}
}
1:{
123: {
name: "Chinga"
}
}
2:{
123: {
name: "Chinga"
}
}
.
.
.
You currently push an object in an array everytime you call your writeArray method, which is not the objective.
As you want to edit an object, using it as a map pretty much, you should access the key (id) you want directly and set the desired value.
finalArray[id] = name;
when I call the method push, it just creates a new item with a key
0,1,2...
push will always add a new item, you need to first check if the item already exists.
function writeArray(id, name){
var index = finalArray.findIndex( function(item, index){
return Object.keys( item )[0] == id;
});
//existing logic
var array = {
[id]:{
name: name
}
};
if ( index == -1 )
{
finalArray.push(array);
}
else
{
finalArray[index] = array;
}
}
What you want is not an array, but an object.
// Initialize object.
var finalObject = {}; /* Changed [] to {} */
function writeToObject(id, name){
finalObject[id] = name;
};
If you still want to use an array, just write finalArray[id] = name but if you got 123 as a number (read: index), that will automatically create empty spaces up to index 123.
I think there are two approaches you can use here:
Instead of an array you can just use an object which simplifies the code pretty much:
finalObject = {};
finalObject[id] = name;
// Structure
finalObject = {'123': 'Jason', '1234': 'John'}
However, if you have to use an actual array, the solution would be to iterate through the array and check if an object with the given ID already exists and if so then modify the name property of it other case just push a new object to the array.
// Structure
finalArray = [{id: '123', 'Jason'}, {id: '1234', 'John'}]
Both could be valid solutions depending on your use case.

Categories