Hello I have an empty array, then I push inside objects, but is not getting updated, it going back to empty again. this on node.js. i need to get as the first argument - from the commend line one of three string that do something to the array : 'add' to add new item to the array, 'delete' for delete frm the array and and 'update' for update the array . second argument is name of the book,third argument author, and last arugmnt pages.
let arrayOfBooks = [];
// Assign places to the array
let whichArgument = process.argv[2]
let name = process.argv[3];
let author = process.argv[4];
let pages = Number(process.argv[5]);
// Function constructor
function Book(name,author,pages) {
this.name = name;
this.author = author;
this.pages = pages;
}
// Add function
const addBook = (arrayOfBooks)=> {
arrayOfBooks.push(new Book(name, author, pages));
return arrayOfBooks
}
let result = addBook(arrayOfBooks);
Your method works, but maybe you are loosing the reference by using the same name to the array and the params. But anyway, as the method .push does not return an updated array, just it modifies the same array instance, you don't need to return the pushed array, just use it.
const arrayOfBooks = [
{book: 1},
{book: 2},
{book: 3},
{book: 4},
]
const addBook = (list, book) => {
list.push(book)
}
addBook(arrayOfBooks, {book: 5, isTheNewOne: true})
const result = arrayOfBooks
console.log(result)
// Array with 5 elements now
See in fiddle
Why is the below returning undefined? Shouldn't I just get back [{name:'bug']?
var a= [{name:'dark'},{name:'bug'}]
a.map(function (obj) {
if (obj.name !== 'dark'){
return obj
}
})
//returns [undefined,{name:'bug}]
.map means you are mapping something for every item in an array. If you do not return anything, it will return undefined
If you wish to get certain values based on condition, you should use .filter
var a = [{
name: 'dark'
}, {
name: 'bug'
}]
var b = a.filter(function(obj) {
return obj.name !== 'dark'
})
console.log(b)
Usage
Map: if you wish to get some property of an object from an array of objects.
Filter: If you wish to get specific values based on a condition. This will return array.
Find: If you wish to get only first matching value. This will return element and not array.
forEach: If you wish to loop over array and do specific processing.
Note: Most of array functions have compatibility issues and you should check it before using it.
References
map: The map() method creates a new array with the results of calling a provided function on every element in this array
Filter: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
you can use filter like this :
var a= [{name:'dark'},{name:'bug'}];
var b = a.filter(item => item.name != 'dark');
console.log(b); // [ { name: 'bug' } ]
I have an array like this:
var myArray = new Array();
myArray['foo'] = {
Obj: {
key: value
}
};
myArray['bar'] = {
Obj: {
key: value
}
};
When I do console.log(myArray) I just get empty [ ]. And when I try to iterate the array using jQuery's each the function doesn't run.
How can I get the 'foo' and 'bar' parts of the array?
Example code:
console.log(myArray); // [ ]
jQuery.each(myArray, function(key, obj) {
console.log(key); // should be 'foo' following by 'bar'
});
In addition, why does this work:
jQuery.each(myArray[foo], function(obj, values) {
// Why does this work if there are no associative arrays in JS?
});
you can get keys by:
Object.keys(variable name);
it returns array of keys.
You need to define it as an object if you want to access it like that:
var myObj= {};
myObj.foo = ...;
myObj.bar = ...;
Now you can access the properties like myObj["bar"] or myObj.bar
Note:
To loop through all the properties it's wise to add an additional check. This is to prevent you from looping through inherited properties.
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// Do stuff.
}
}
Array is a collection where each element has an index.
To add element to array you can use push method
myArray.push('someValue');
or set element by index (if length of array < index):
myArray.push('someValue1');
myArray.push('someValue1');
myArray[0] = 'new someValue1';
Note that array is an instance of Object class, so you can add/edit any property of this object:
myArray.foo = '1';
myArray['bar'] = '2';
In this case you will not add new element to array, you defining new properties of object.
And you don't need to create object as Array if you don't wont to use indexes.
To create new object use this code:
var myObj = {};
To get all properties of object see
How to get all properties values of a Javascript Object (without knowing the keys)?
var myArray = {};
myArray['foo'] = { 'key': 'value' }
myArray['bar'] ={ 'key': 'value' }
console.log(myArray)
jQuery.each(myArray['foo'], function(obj, values) {
console.log(obj, values)
});
Demo
With your Array of Objects you could use this function:
var getKeys = function(obj) {
if (!(typeof obj == "object")) return [];
var keys = [];
for (var key in obj) if (obj != null && hasOwnProperty.call(obj, key)) keys.push(key);
return keys;
};
getKeys(myArray) would give you an array of your Keys.
This is basically a cleared up version of underscores _.keys(myArray) function. You should consider using underscore.
// $.each() function can be used to iterate over any collection, whether it is an object or an array.
var myArray = {};
myArray['alfa'] = 0;
myArray['beta'] = 1;
$.each(myArray, function(key, value) {
alert(key);
});
Note: checkout http://api.jquery.com/jQuery.each/ for more information.
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());
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);