I am trying to add an element to a js object - javascript

I try to push key value pairs to an object. the key value pairs have to be added to a certain index which is given by the e.vatRecord.debit. This variable is working properly if I log this on console. But in combination it does not work.
journalByAccounts = {}; // define an object
data.entries.forEach(function(e) {
journalByAccounts[e.vatRecord.debit].push({
valuta: e.valuta,
text: e.text,
debit: e.mainRecord.amount
});
});

Either you first need to initialize the object journalByAccounts[e.vatRecord.debit] to an empty array [] because you can't push into undefined (expecting that it magically becomes an array):
journalByAccounts = {};
data.entries.forEach(function(e) {
if (!journalByAccounts[e.vatRecord.debit])
journalByAccounts[e.vatRecord.debit] = [];
journalByAccounts[e.vatRecord.debit].push({
valuta: e.valuta,
text: e.text,
debit: e.mainRecord.amount
});
});
The if is being done to make sure that it still goes right if e.vatRecord.debit can contain the same value more than once, creating the array only once for each value.
Or if you don't actually want an array, then you should do an assignment:
journalByAccounts[e.vatRecord.debit] = {
valuta: e.valuta,
text: e.text,
debit: e.mainRecord.amount
};

journalByAccounts = []; // define an object
you must define an empty array, not an obj.

Related

How to make array of objects in JS

I want to send a multi level array via AJAX. so I tried to make an object of objects as follow:
var info = {};
info.pickup = {};
info.pickup.contact = {};
info.pickup.items_quantity = {};
info.pickup.items = {};
info.delivery = {};
info.delivery.contact = {};
info.delivery.level = {};
then I started filling the objects, for example:
$('.operation-create .pickup .contact-details').each(function () {
var arr = {};
arr['contact_name'] = $(this).find('input[name="pickup-contact-name"]').val();
arr['contact_phone'] = $(this).find('input[name="pickup-contact-phone"]').val();
arr['pickup-suburb'] = $(this).find('select[name="pickup-suburb"]').val();
arr['single-pickup-address'] = $(this).find('input[name="single-pickup-address"]').val();
info.pickup.contact.push(arr);
});
info.pickup.push(info.pickup.contact);
etc...
However unfortunately it didn't work. I get this error:
info.pickup.contact.push is not a function
What I should do here? What is the right way to send this array via AJAX?
You need an array as value
info.delivery.contact = [];
// ^^
The last line
info.pickup.push(info.pickup.contact);
makes no sense, because you have properties in this object. For pushing some values, you need an array
info.pickup = [];
// ^^
An while you already have an array for info.pickup.contact, you could skip the line
info.pickup.push(info.pickup.contact);
It's important to understand the difference between an object and an array.
{} creates a plain object, which doesn't have a push method.
[] creates an array, which is an object with additional features, including a push method.
Looking at your code, at the least, you want info.pickup.contact and probably info.delivery.contact to be arrays (I'm guessing probably items_quantity and items as well, but it's hard to be sure). (The thing you call arr in your looping function isn't an array and doesn't need to be.)
So at a minimum:
info.pickup.contact = [];
// -------------------^^
and
info.delivery.contact = [];
// ---------------------^^
You also want to remove the info.pickup.push(info.pickup.contact); at the end; info.pickup isn't an array, and you've already put the contacts in info.pickup.contact.
Side note: Your code might also benefit from using object initializers:
var info = {
pickup: {
contact: [],
items_quantity: {}, // This might also want to be an array
items: {} // This might also want to be an array
},
delivery: {
contact: [],
level: {} // No idea what you're doing with this, so...
}
};
$('.operation-create .pickup .contact-details').each(function () {
info.pickup.contact.push({
contact_name: $(this).find('input[name="pickup-contact-name"]').val(),
contact_phone: $(this).find('input[name="pickup-contact-phone"]').val(),
pickup-suburb: $(this).find('select[name="pickup-suburb"]').val(),
single-pickup-address: $(this).find('input[name="single-pickup-address"]').val()
});
});
...but it's a matter of style.
info.pickup.contact = {};
That is an object declaration, not array.
An array should be
info.pickup.contact = []; // `[]`
As the other answers have stated you need to change the contact from an object (ie. {}) to an array ([]).
Also note that you can use jQuery's map() to build the array and make the code a little more succinct:
info.pickup.contact = $('.operation-create .pickup .contact-details').map(function () {
return {
contact_name: $(this).find('input[name="pickup-contact-name"]').val(),
contact_phone: $(this).find('input[name="pickup-contact-phone"]').val(),
pickup-suburb: $(this).find('select[name="pickup-suburb"]').val(),
single-pickup-address: $(this).find('input[name="single-pickup-address"]').val()
}
}).get();
You need an array in order to push a element into it. Here it is object so obviously it is not possible for you to add.
if you want to add then make it as array like
info.pickup.contact = [];
now if you add then it will accept. After adding, your array will be like follows..
info.pickup.contact = [];
info.pickup.contact.push("Sample");
{"pickup":{"contact":["Sample"]}}

cant seem to loop through object keys

I have an object through which im trying to loop through using for..in. But it gives me "0" as values instead of the object keys such as piidata, location, risklevel etc.
var srcObj = [{
location: "34",
piidata: "sdafa",
risklevel: "Medium"
}]
for (var prop in srcObj) {
console.log(prop);
}
srcObj is an array, as evidenced by the []. Inside it is an object at index 0.
Your "srcObj" is an array. This is indicated by the wrapping [ ... ]. If you console.log srcObj[0], you should get the object itself.
while you are looping the javascript object it's return the index/key of object
so if you are trying to get value of each key try.
for( var prop in srcObj )
{
console.log(srcObj[prop]);
}
if you are trying to get each key name then try this one
for( var prop in srcObj )
{
console.log(prop);
}
All you need to do
for (var prop in srcObj) {
console.log(srcObj[prop]);
console.log(srcObj[prop]["risklevel"]); // --> Medium
var keyNames = Object.keys(srcObj[prop]); // --> return keyNames as array
console.log(keyNames[0], keyNames[1]); // --> location piidata
}
Your srcObj is an array. You can tell by the square brackets [] it's enclosed in. But Chrome says Object. Right. Javascript types are a little strange. Check out this page.
If you want to access the key/values in the object, you can specify the index of the object within the array. srcObj[0] in this case. If you want to get the object out of the array and deal with it just as an object, you can do something like this:
var trueObject = srcObj.shift()
Which removes and returns the first element of an array and assigns it to your variable.
Your srcObj is actually an array (identified by the [ and ] literals) which contains an object as its only element.
To access the parameters of the single object inside the array, use the following syntax:
for( var prop in srcObj[0] )
{
console.log(prop);
}
jsFiddle Demo

How to get correct order of js object?

I have the question about js obj order:
When I define:
var objJSON = {};
objJSON[31] = '123'; ------------- (1)
objJSON[23] = '456'; ------------- (2)
And alert the object:
alert(JSON.stringify(objJSON, null, 4));
It shows:
"
{
"23":"456",
"31":"123"
}
"
I would like to get the object by the order of inserting:
"
{
"31":"123",
"23":"456"
}
"
How to do so?
The properties of an object don't have a guaranteed ordering. If the key, value and position is important, I would recommend an array of objects instead:
var x = [];
x.push({
key: 23,
value: '123'
});
x.push({
key: 31,
value: '456'
});
JSON.stringify(x); // [{"key":23,"value":"123"},{"key":31,"value":"456"}]
JavaScript objects cannot be counted on to maintain order. You will likely want to use an array instead, which will preserve index order.
Just change {} to [] in your first line.
var objJSON = [];
You're using an object (which can be thought of as a "map" for this purpose), when you need an array. Objects do not guarantee order. What if you happen to add another property later? It will also skew the order. Try using an array/list/vector of objects instead. For example:
var array = [];
array[0] = { 31: '123' };
array[1] = { 23: '456' };
A dictionary is a data structure that does not preserve order by definition.
You will need to sort the dictionary yourself by key or by value.
Check this:
sort a dictionary (or whatever key-value data structure in js) on word_number keys efficiently
try this:
var objList = [];
objList.push({"31" : "123"});
objList.push({"23" : "456"});
alert(JSON.stringify(objList));
You need to put the key-value pairs in an array so you get
{
"array": ["31":"123", "23":"456"]
}

How to add an element containing fields to an array

Using javascript, how can I add to an array an element which contains fields (pairs of field name and field value)?
The purpose of this is that each element will later be inserted as a row to a DB, using ajax.
Just to make sure - after the array is ready I should be able to access a field this way:
shopsArray[4].shopName
Edit:
It's working with Pointy's answer but I still have a problem:
shopsArray.push( { shopId: 1, shopAddress: $('#newAddress' + j).val() } );
The first value is inserted fine, but the second one has a problem.
If I alert $('#newAddress' + j).val() than I get the correct value which has been inserted in the field in the webpage.
But if I alert shopsArray[lastElementNumber].shopAddress than I get undefined.
Can you see what's the problem here?
Edit 2:
More elaborate code:
// save changes in main shop
shopsArray[0].shopName = $('#mainName').val();
shopsArray[0].shopAddress = $('#mainAddress').val();
// save secondary branches to array
for (var i=1; i<shopsArray.length; i++){
shopsArray[i].shopName = $('#secondaryName' + i).val();
shopsArray[i].shopAddress = $('#secondaryAddress' + i).val();
}
// save new branches to array
for (var j=1; j<=newshopsCounter; j++){
var bName = $('#newName' + j).val();
shopsArray.push({shopId: -1, userId: shopsArray[0].userId, shopName: bName, shopAddress: $('#newAddress' + j).val()});
alert(bName);
alert(shopArray[1].shopName);
alert(shopsArray[1].shopId);
}
The first and third alerts give the correct values. The second one gives undefined.
You mean something like
shopsArray.push({ shopName: "Fred", value: "Ethel" });
?
edit — now that I know that this is the sort of thing you want to do, I'll clarify.
JavaScript has an "object literal" syntax that allows objects to be created directly as values. The syntax involves a list of property names and values, with the names and values separated by a colon and each pair separated by commas. Thus:
var anObject = { someProperty: "the value" };
creates an object with one property and assigns it to the variable "anObject". That's effectively the same as:
var temp = new Object();
temp["someProperty"] = "the value";
var anObject = temp;
The "value" part of a property in an object literal can be any expression, but the property name must be either a string constant or an identifier (and in either case, it's treated like a string constant). Thus, you can create an object with a property whose value comes from calling some function:
var fancyObject = { "temperature": getTemperature() };
Object literal expressions are values, and can be used anywhere you can use an expression, including function call arguments. Therefore, to add an object to an array, it's possible to call the array ".push()" function and use an object literal as the argument, as in the first example:
shopsArray.push({ shopName: "Cheese Shoppe", shopPhone: "111 222 3232" });
You can even include object literals inside another object literal, as the value of a property:
shopsArray.push({
shopName: "Cheese Shoppe",
shopAddress: {
street1: "207 High Street",
street2: "No. 5",
city: "Austin",
state: "TX"
}
});
You would simply create a hash inside an array to achieve that:
var shopsArray = [
{
shopName: 'value1'
}, {
shopName: 'value2'
}
];
If you have an existing array, use push:
shopsArray.push({ shopName: 'value' });
you can do something like this:
var arr = new Array();
arr['field_name'] = 'field_value';
//to access it on ajax
for (var i in arr){
//field_name is in "i"
//field_value is in arr[i]
}

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