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]
}
Related
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.
Problem:
Declare a variable named myArray and assign it to an empty array.
Great! Now populate myArray with two strings.
Put your full name in the first string, and your Skype handle in the second.
Next, declare a function named cutName. It should expect a parameter name.
cutName should return an array by breaking up the input string into individual words. For example "Douglas Crockford" should be returned as ["Douglas", "Crockford"]
Declare a new variable named myInfo and assign it to an empty object literal.
Add the following three key-value pairs to myInfo:
Key: fullName
Value: The result of calling cutName on the name string within myArray.
Key: skype
Value: The Skype handle within myArray.
Key: github
Value: If you have a github handle, enter it here as a string. If not, set this to null instead.
My code
var myArray = ['Isaiah Sias', 'isaiahsias15689'];
function cutName(name){
var splitString = name.split(myArray[0]' ');
return splitString;
}
var myInfo{
fullName = cutName(myArray[0]),
skype = myArray[1],
github='#kakashihatake',
};
Once again I am not sure where I am messing up. I have been working on this problem for a few days now and find myself a little frustrated.
You are very close, you have made a small mistake in the cutName function.
The string.split method takes only 1 parameter, the string to split by. You've tried to pass in the array element as well. Get rid of it! (Keep in mind that the thing we are splitting, name, has been assigned the array element as its value during the function call)
var splitString = name.split(myArray[0]' ');
becomes
var splitString = name.split(' ');
One other issue, you'll need to change your object definition a bit. You have a missing = between myInfo and the start of the object literal. And, when setting property names and values in an object literal you need to use colon instead of equals, so your object
var myInfo{
fullName = cutName(myArray[0]),
skype = myArray[1],
github='#kakashihatake',
};
becomes
var myInfo = {
fullName: cutName(myArray[0]),
skype: myArray[1],
github: '#kakashihatake'
};
var myArray = ['Isaiah Sias', 'isaiahsias15689'],
github = '#kakashihatake';
function toObject(){
return {
fullName: myArray[0].split(' '),
skype: myArray[1],
github: github
}
}
console.log(toObject());
How can I access Name's value and assign it to an variable?
var arr = [
{Name: "Jason",
Title: "Student",
Image: "asdf",
Status: "Happy"}
];
Try this:
var [{Name: name}] = arr;
This uses ES6 destructuring assignment.
First, the outermost [] is a way of referring to an array on the right hand side (in this example, arr). Things placed within these square brackets (here's there's only one) refer to the first, second, and succeeding values of that array. So here, the {Name: name} portion refers to the first (0th) element of the array. In other words, it is equivalent to
var {Name: name} = arr[0];
The inner {} is a way of referring to objects and picking them apart. {Name: name} says to find the Name property of the object being picked apart. Then the : name part says to rename it to name. Since all this is occurring in the context of a var statement, the result is declare a new variable with the name name and assign the value being picked out to it.
Here's the more detailed sequence:
var // Start a variable declaration
[ // Pick apart an array on the RHS, starting with 1st element
{ // Pick apart an object
Name // Find the property named `Name` in that object
:name // Rename it; this is the variable that will be declared!
} // Done picking apart the object
] // Done picking apart the array
= arr; // Specify the thing to deconstruct
Access the element at index 0 of array using bracket notation, then access property name Name of object using dot or bracket notation
var arr = [
{Name: "Jason",
Title: "Student",
Image: "asdf",
Status: "Happy"}
];
var name = arr[0].Name; // alternatively, `arr[0]["Name"]`
var arr = [
{Name: "Jason",
Title: "Student",
Image: "asdf",
Status: "Happy"}
];
var myname = arr[0]['Name'];
console.log(myname);
if I have an array like this:
var msg = [ {name: ["a1", "a2"], value: "this is A"},
{name: ["b1", "b2"], value: "this is B"},
...
]
The array contains global errors messages for client-side form validations. I have managed to pass in faulty inputs (e.g. "a1") and now am wondering how to get the corresponding message out of my ill-constructed array.
Question
What would be the best way to loop through this array? for example, if I have "a1" as parameter passed into my function, how do I extract "this is A" as corresponding message?
inArray doesn't really help, because I need the corresponding message and not the position of a1. I'm also not sure if this is the best way to store my error messages... ideas welcome!
Thanks for help!
Re-arrange your data structure:
var my_param = 'b1';
// This is an object, so we can have key/value pairs
var error_codes =
{
'a1': 0,
'a2': 0,
'b1': 1,
'b2': 1
};
// This is an array because we only need values
var error_messages =
[
'This is A',
'This is b'
];
alert(error_messages[error_codes[my_param]]);
This makes it really easy to set up new error codes and messages, and is extremely easy to understand. The only gotcha is error_codes[my_param] - it's an object, but we can't do error_codes.my_param because it'll look for the element called 'my_param', so using array notation, we can look up the object key.
The only other potential trap is making sure you don't have any trailing commas:
var error_codes = { 'a1': 1, }; // NO!
Also knows as the trailing comma of death!
This would be how I'd do it
var myMsg = findMsg('a1')
function findMsg(msgType){
msg.forEach(function(obj){
if(inArray(msgType, obj.name) !== -1){
return obj.value
}
})
}
function inArray(key, obj){
return obj.join().indexOf(key)
}
$.each is the jQuery way for taking action on each element of an array or each enumerable property of an object.
var value;
$.each(msg, function (i, el) {
if (el.name.indexOf(name) >= 0) {
value = el.value;
return false; // Stops iteration.
}
});
If name is "a1" then after running the above, value === "this is A".
Nice and simple:
var getMessage = function (name)
{
var msg = [ ... ];
for(var i = 0; i < msg.length; ++ i)
if (msg [i].name.indexOf (name) != -1)
return msg [i].value;
}
Returns either the corresponding message or undefined if the name wasn't found.
You may need a shim for indexOf depending on which browsers you want to support:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
I am trying to create an object - that each parameter inside it is another object:
var divTextPerScreenWidthMap = new Object(
{'360','click'},
{'480','click it'},
{'768','click it right'},
{'1024','you know you want to click it'},
{'1280','click this button which is very long will help you'}
);
This is not working since I am getting an error. how do I need to write it to make it work? Should I change the outer object into an Array and how?
You have syntactical errors.
First of all object literal follows the syntax below:
var literal = {
"Name": "value",
"Array": [],
"NestedObject": {}
};
Name value separator is the colon, not comma.
EDIT
The above code might be rewritten as follows
// declaration via array initializer
var myArray = [
// name : value syntax
{'360': 'click'},
// values separated by comma
{'480': 'click it'},
{'768': 'click it right'},
{'1024': 'you know you want to click it'},
{'1280': 'click this button which is very long will help you'}
]
however at this point you cannot access your objects via i'ts names like this:
var firstObject = myArray[0];
// will throw an error
firstObject.360 = "not click";
You can only use it as follows
firstObject["360"] = "not click";
Hence I suggest you to name the properties according to variable naming rules.
In javascript object is a simple map. It is better to use literal {} instead od new Object();
var myObj = {
prop : {},
prop2 : {}
}
Don't create an Object via its constructor, use the literal syntax {}.
Also, objects have keys and properties. Your objects seem to only have values. Did you mean to use Arrays?
You completely forgot to give keys for your values. If you don't want to use keys, use arrays:
var divFoo = [
[360, "click"],
[480, "click it"] // et cetera
];
This would give you an array of arrays. For instance, divFoo[0][0] == 360
If you want keys, use an object:
var divFoo = {
"360": "click",
"480": "click" // et cetera
}
This gives you simple object. divFoo[360] == "click"
Or you could use an array of objects for more descriptiveness:
var divFoo = [
{time: 360, text: "click"},
{time: 480, text: "click it"} // et cetera
];
In this case, divFoo[1].text == "click it".
Also, a few hints:
Don't use new Object or new Array. They're redundant.
There's no need to quote integers if they're used as values.
It would make sense to represent your collection of objects as an array:
var divTextPerScreenWidthMap = [
{360:'click'},
{480:'click it'},
{768:'click it right'},
{1024:'you know you want to click it'},
{1280:'click this button which is very long will help you'}
];
//You could iterate over your array of objects with a for loop:
var i, value;
for (i=0; i < divTextPerScreenWidthMap.length; i++) {
value = divTextPerScreenWidthMap[i];
console.log(value);
};
//Alternatively, you could represent your data structure as one object:
var divTextPerScreenWidthMap = {
360:'click',
480:'click it',
768:'click it right',
1024:'you know you want to click it',
1280:'click this button which is very long will help you'
};
//So now if you have a screen width, you can quickly get back the corresponding message:
var screenWdith = 360;
alert(divTextPerScreenWidthMap[screenWidth]);
You can also created nested objects like this:
let obj1 = {};
obj1['title'] = 'Vehicles';
let obj2 = {};
obj2['name'] = 'Honda City';
obj1['cars'] = obj2;
console.log(obj1);
Create a method in object, create a new object in that method and return it.
const obj = {
one: "one is just a property",
two: function(){
const newObject = {
three: "now two will return new a new object"
}
return two;
}
}