You need to push a newly created item to your array like below:
CoinArray.push(new Coin.Create('123));
On the other hand if you want to create an object with keys ids and values corresponding Coin objects, you should try this:
CoinDictionary = {};
CoinDictionary['123'] = new Coin.Create('123');
Note:
I think that you should refactor a bit the Coin if you want to use it as a constructor function:
function Coin(id){
this.id = id;
}
Doing this change you can use it as below:
CoinArray.push(new Coin('123'));
function Coin(id){
this.id = id;
}
var CoinArray = [];
CoinArray.push(new Coin('123'));
CoinArray.push(new Coin('456'));
CoinArray.push(new Coin('789'));
console.log(CoinArray);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Update
At the end I want to have array with object and for example I will take first el of array, and execute other method from Coin class.
For this purpose If I were you I would have gone with the creation of an object with keys the ids and values references to Coin objects:
function Coin(id){
this.id = id;
}
Coin.prototype.start = function(){
console.log("game with id "+this.id+" started.");
}
Coins = {}
Coins['123'] = new Coin('123');
Coins['456'] = new Coin('456');
Coins['789'] = new Coin('789');
Coins['456'].start();
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from Christos on Stack OverflowYou need to push a newly created item to your array like below:
CoinArray.push(new Coin.Create('123));
On the other hand if you want to create an object with keys ids and values corresponding Coin objects, you should try this:
CoinDictionary = {};
CoinDictionary['123'] = new Coin.Create('123');
Note:
I think that you should refactor a bit the Coin if you want to use it as a constructor function:
function Coin(id){
this.id = id;
}
Doing this change you can use it as below:
CoinArray.push(new Coin('123'));
function Coin(id){
this.id = id;
}
var CoinArray = [];
CoinArray.push(new Coin('123'));
CoinArray.push(new Coin('456'));
CoinArray.push(new Coin('789'));
console.log(CoinArray);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Update
At the end I want to have array with object and for example I will take first el of array, and execute other method from Coin class.
For this purpose If I were you I would have gone with the creation of an object with keys the ids and values references to Coin objects:
function Coin(id){
this.id = id;
}
Coin.prototype.start = function(){
console.log("game with id "+this.id+" started.");
}
Coins = {}
Coins['123'] = new Coin('123');
Coins['456'] = new Coin('456');
Coins['789'] = new Coin('789');
Coins['456'].start();
Run code snippetEdit code snippet Hide Results Copy to answer Expand
class Coin {
constructor(id) {
this._id = id;
}
start() {
console.log('starting');
}
}
CoinArray = [];
CoinArray['123'] = new Coin(123);
CoinArray['333'] = new Coin(333);
CoinArray['123'].start();
Also i would suggest managing id's that way:
let id = 0;
class Coin {
constructor() {
this._id = id++;
}
start() {
console.log('starting');
}
}
CoinArray = [];
CoinArray.push(new Coin());
CoinArray.push(new Coin());
CoinArray[0].start();
Efficient way of iterating over a array of objects in javascript/node.js - Stack Overflow
node.js + Object Array - javascript
how to create an array of objects in node.js - Stack Overflow
Sending an array of objects in a node js post request
You can use the array filter or find methods
ArrPerson.find(p=>p.name=='john')
ArrPerson.filter(p=>p.name=='john')
The find method searches the array from the beginning and stops when it finds one element that matches. In the worst case where the element that is being searched is the last in the array or it is not present this method will do O(n).This means that this method will do n checks (n as the length of the array) until it stops.
The filter method always does O(n) because every time it will search the whole array to find every element that matches.
Although you can make something much more faster(in theory) by creating a new data stucture.Example:
var hashmap = new Map();
var ArrPerson = [];
ArrPerson.push(new Person("john",12,"M1"));
hashmap.set("john",true);
This ES6 Map will keep an index of the whole array based on the names it contains. And if you want to see if your array contains a name you can do:
hashmap.has('john')//true
This approach will do O(1). It will only check once on the map to see if this name exists in your array. Also, you can track the array indexes inside the map:
var index = ArrPerson.push(new Person("john",12,"M1"));
var map_indexes = hashmap.get("john");
if(map_indexes){
map_indexes.push(index-1);
hashmap.set("john",map_indexes);
}else{
hashmap.set("john",[index-1]);
}
map_indexes = hashmap.get("john"); //an array containing the ArrPerson indexes of the people named john
//ArrPerson[map_indexes[0]] => a person named john
//ArrPerson[map_indexes[1]] => another person named john ...
With this approach not only you can tell if there is a person in the array with the specific name but you can also find the whole object with O(1). Take into account that this map will only index people by name if you want other criteria you need another map. Also keeping two data structures synchronized is not easy(deleting one element from array should also be deleted from the map, etc)
In conclusion, as always increasing speed ends sacrificing something else, memory and code complexity in our example.
- use ES5 array methods like map ,filter ,reduce etc
- use forEach
- native for loop
Example : filter , map, reduce etc. methods iterate over each item or object in an array,
ArrPerson.filter(function(item){
console.log(item)
});
forEach : also iterates over each item/object in an array
ArrPerson.forEach(function(key,value){
console.log(key);
console.log(value)
})
The question said huge array , so
native for loop is way faster than any of the above and caching the length can improve by a few ms (milliseconds).
https://jsperf.com/native-map-versus-array-looping
for(var i = 0, len = ArrPerson.length; i < len; i++){
}
I am trying to send an array of objects in a post request but when I try to access the array with req.body it is just showing {object} and none of the objects content is being sent. Is there something wrong with my request?
here is my request:
Post http://localhost:3000/users/newOrder Content-Type: application/json
{ "firstName": "Craig", "lastName": "Mar", "address1": "10 a st", "address2": "apt 2", "email": "c@yahhoo.com", "town": "red bank", "state": "nj", "zip": "07701", "shippingCost": 12.00, "orderCost": 25.00, "productsArray": [{ "id": "4a482549-79aa-4798-8a3b-a19746cd645a", "title": "Microsoft Xbox X/S Wireless Controller Robot White", "price": 57, "quantity": 1, "total": "57.00", "image": "https://storage.googleapis.com/fir-auth-1c3bc.appspot.com/1692255251854-xbox.jpg" }, { "id": "827ab3f1-b5d5-436a-93cc-7a4a28aefd3b", "title": "Sony WH-1000XM3 Bluetooth Wireless Over Ear Headphones with Mic (Silver)", "price": 773, "quantity": "2", "total": "1546.00", "image": "https://storage.googleapis.com/fir-auth-1c3bc.appspot.com/1692947383286-714WUJlhbLS.SL1500.jpg" }
]
}
a console log of the req.body is the following:
{ firstName: 'Craig', lastName: 'Mar', address1: '10 a st', address2: 'apt 2', email: 'c@yahhoo.com', town: 'red bank', state: 'nj', zip: '07701', shippingCost: '12', orderCost: '25', productsArray: [ '[object Object]', '[object Object]' ] } if i try to access the values of the objects in the products array with dot notation i am getting undefined any ideas where i am going wrong? I have also tried a curl request but get the same result.
You can use the Array.prototype.map method of an array.
Simply call a map over the array, get the data in order from the array item and return the object you want in the map function.
const arr = [
["Benni", 24, "Whatever"],
["Paul", 23, "Whatever"]
];
const remapped = arr.map((data) => {
const [name, age, Text] = data;
return {
name,
age,
Text,
};
});
console.log(remapped);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
pretty easily:
let result = inputArr.map( innerArr => {name: innerArr[0], age: innerArr[1], Text: innerArr[2]});
I would propose this solution based on a dynamic number of keys:
var arr = test.map(function(obj){
return Object.keys(obj). // convert object to array of keys
reduce(function(arr, current){arr.push(obj[current]); return arr}, []); // generate a new array based on object values
});
This can be done using Array.map() as follows:
var actual = []
test.map(function(object) {
actual.push(objectToArray(object))
})
function objectToArray(obj) {
var array = []
// As georg suggested, this gets a list of the keys
// of the object and sorts them, and adds them to an array
var obj_keys = Object.keys(obj).sort()
// here we iterate over the list of keys
// and add the corresponding properties from the object
// to the 'array' that will be returned
for(var i = 0; i < obj_keys.length; i++) {
array.push(obj[obj_keys[i]])
}
return array
}
The function objectToArray takes any object and turns it into an array so that it can be flexible regardless of the keys within the object.
Use Object.assign for this so that you can combine the array with the common id value, use find having condition that compares the id of both the objects.
var data1 =[ {foo:'2',box:'yes',id:'1234'},{foo:'34',box:'no',id:'1235'} ];
var data2 =[{key:'value',key2:'value2', id:'1234'},{key:'value',key2:'value2', id:'1235'}];
data1.map(x => Object.assign(x, data2.find(y => y.id == x.id)));
console.log(data1);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Since you have same key name multiple times which is ignored by the JSON object so I have taken a new property name
key2for this example.
building on @Ankit answer, you can use the spread operator too !! something like this
var data1 =[ {foo:'2',box:'yes',id:'1234'},{foo:'34',box:'no',id:'1235'} ];
var data2 =[{key:'value',key2:'value2', id:'1234'},{key:'value',key2:'value2', id:'1235'}];
const arr = data1.map(x => ({ ...x, ...data2.find(y => y.id == x.id)}));
console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand