push Object in array in $.each - javascript

Maybe I'm just blind, but I'm struggling for a good amount of time now:
I have a small piece of JS-Code here:
var linkInput = $('#Link input.gwt-TextBox').val();
var parentRow = $('#Link').parent().parent();
var links = linkInput.split("|");
// hide text-input
$(parentRow).hide();
// get rid of empty elements
links = links.filter(Boolean);
var aSites = [];
var oSite = {};
$(links).each(function (k, v) {
splits = v.split(".");
domainName = splits[1];
oSite.name = domainName;
oSite.url = v;
aSites.push(oSite);
});
console.log(aSites);
To specify: Get the value of an input-field, hide the row afterwards and save all the values in an object, which is then pushed into an array.
The parameter, taken from the console-tab of google Chrome:
var links = ["www.myshop1.de/article/1021581", "https://www.myshop2.de/article/1021581"] [type: object]
I thought, I iterate through all elements of this object (in that case 2 times), push the values into an object and the object into an array, to have access to all of them afterwards.
At some point however, I seem to override my former values, since my output looks like this:
0: {name: "myshop1", url: "https://www.myshop1.de/1021581"}
1: {name: "myshop2", url: "https://www.myshop2.de/1021581"}
length: 2
__proto__: Array(0)
Where is my mistake here? Is there a smarter way to realize this?
On a sidenote:
I tried to use only an array (without adding an object), but it seems like I
can't use an associative key like this:
var myKey = "foo";
var myValue = "bar";
myArray[myKey] = myValue

You should move this:
var oSite = {};
...inside the each callback below it, because you need a new object in each iteration.
Otherwise you are mutating the same object again and again, pushing the same object repeatedly to the aSites array, which ends up with multiple references to the same object.
Not related, but you can use $.map to create your array (or vanilla JS links.map()):
var aSites = $.map(links, function(v) {
return { name: v.split(".")[1], url: v };
});

Related

how to create array of json object without key in javascript

I want to create an array of JSON object without a key.How can this is achieved ..??
for example [{8,0,2}, {20,0,2}].
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push({hh,mm,qty})
it gives data like [{hh:9,mm:8,qty:2}]
I want array like [{9,8,2},{9,3,4}]
You example uses a new feature of ECMAScript 6 that is the shorthand syntax for initialising object properties. This line in your example:
data.push({hh,mm,qty});
is equivalent to this verbose one:
data.push({hh: hh, mm: mm, qty: qty});
An object in JavaScript will always have keys and values. There is no way to save just values in a plain object. However, there are two other solutions.
One is using an array:
data.push([hh, mm, qty]);
Note the square brackets substituting the curly ones. This will obviously push an array of three values onto the data array. When retrieving the values, you can just refer to their index, as an array's items will always retain their indices:
var data2 = [hh, mm, qty];
var hh2 = data2[0];
var mm2 = data2[1];
var qty2 = data2[2];
Another way of just "saving the values" is using a set, though the construction of a Set object will still require passing it an array:
data.push(new Set([hh, mm, qty]));
Accessing the data is less straightforward in this case, as the set will typically only let you iterate it. Unlike similar data structures in other languages, a JavaScript set will retain the order of inserted values. It can therefore be safely converted into an array:
var mySet = new Set([hh, mm, qty]);
var data3 = Array.from(mySet);
var hh3 = data3[0];
var mm3 = data3[1];
var qty3 = data3[2];
You can read more about sets here.
You can wrap it over another JSON object with a key I assume you want a JSON object.
Like this { [{8,0,2}, {20,0,2}] } but this with a problem - It is not a valid JSON.
I had a similar problem for one of my scenario. Then I realised
A top level JSON can't exist without a key!
Consider this example, you have another KV pair in JSON and also this array.
{
"somekey" : "somevalue",
[ {8,0,2}, {20,0,2} ]
}
You can fetch "somevalue" with the key "somekey". But how would you access the array? you can't :(
I would suggest you to use a top level key for the JSON and make this array as value of it's. Example:
{
"my array" : [ {8,0,2}, {20,0,2} ]
}
Without a key value pair, the object was not created. That's why its adding a key using the variable name
Look at this error. Its invalid code
var a = [{8,0,2}, {20,0,2}];
console.log(a)
You could push to an array instead of an object
var data = [];
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push([hh,mm,qty])
console.log(data)
You can't.
Object Literal Property Value Shorthands allow you to create an object where the property names are inferred from the variable names you use to pass the data into.
If you don't have variable names, then there is nothing for the JS engine to use to figure out what the property names should be.
Consider using a function instead.
console.log([time(8,0,2), time(20,0,2)]);
function time (hh, mm, qty) {
return {hh, mm, qty};
}
The result you get at the end makes sense. By doing {hh,mm,qty} you are effectively saying "Use the variable name as the key and its value as the value". It might help us more if you provide an example of how you intend to use the result and access the variables i.e. the shape of the object you want in the end.
That being said, there are a couple alternatives:
Using values as the keys
If you really wanted your object to look similar to {8,0,2} you could use those values as the keys (all keys get converted to strings anyways) so you could do the following:
var example1 = {8:undefined,0:undefined,2:undefined};
var example2 = {8:null,0:null,2:null};
var keys = [];
for(var name in example1) {
keys.push(name);
}
// keys = ["8","0","2"];
var otherKeys = Object.keys(example2);
// otherKeys = ["8","0","2"];
Setting the keys dynamically
var hh = 9;
var mm = 8;
var qty = 2;
var obj = {};
obj[hh] = null;
obj[mm] = null;
obj[qty] = null;
//obj = {9:null,8:null,2:null};
I'm not certain if this solves your problem or answers your question entirely but it might give you some more insight into what is happening and why. The above examples are a common way to create a quick lookup versus a dictionary with would have values in place of null or undefined.

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"]}}

pass array to method with condition

Im using the following code to split array which is working,
I need to pass some value when array
for examle here is split the value to array
var myArr = val.split(/(\s+)/);
and if array in place 2 is empty I need to use the method like following
pass empty array in second arg
var val = process.run(myArr[0], [], options);
if the array place 2 is not empty I need to pass it like following
var val = process.run(myArr[0], [myArr[2]], options);
The second arg is array inside arry with the value of 2
there is nice way to do it instead of if on the method ?
I would create a function, as Dave Newton recommends. I could take the initial val and options as an argument and return the result of process.run:
function runProcess(val, options) {
var myArr = val.split(/(\s+)/);
var argArray = [];
if(myArr[2]) {
argArray.push(myArr[2]);
}
return process.run(myArr[0], argArray, options);
}
Since I don't know what the function exactly does, the name of the function and variables are pretty arbitrary. Feel free to change them to your needs.
If myArr[2] is a flat array and will always be flat, why not...
var val = process.run(myArr[0], [].concat(myArr[2]), options);

JavaScript Two dimensional Array

I am creating javascript two dimensional array
code is :
var field_arr=[];
$(".dr").each(function(index){
Id=$(this).attr("id");
alert(dragId);
topPos=$("#"+ dragId).position().top;
left=$("#"+ dragId).position().left;
parentDiv=$("#"+dragId).parent().attr("id");
parentDiv= parentDiv.split('-');
paId=parentDiv[1];
field_arr[Id]=new Array();
field_arr[Id]['paId']=paId;
field_arr[Id]['top']=topPos;
field_arr[Id]['left']=left;
});
console.log(field_arr);
Output Is:
[undefined, [] left 140 paId "1" top 10
What is problem in It Any help Should be appreciated.
The problem is in the display method of your arrays. The information is there, but both alert and console.log will not show it to you because it is expected that the only interesting properties of arrays are the ones with numeric indexes.
In JavaScript, unlike PHP, objects are used as maps/associative arrays.
First to check that your information is actually there:
$(".dr").each(function(index){
var Id=$(this).attr("id");
console.log(Id, field_arr[Id]['paId'], field_arr[Id]['top'], field_arr[Id]['left']);
});
Now to make make the display methods work you can go about multiple ways, but the best one is to use objects instead:
var field_arr = Object.create(null); // replace with {} if you want to support IE8-
$(".dr").each(function(index){
var id = $(this).attr("id"); // added var to keep variable local
var drag = $("#"+dragId);
field_arr[id] = Object.create(null); // {}
field_arr[id]['paId'] = drag.parent().attr("id").split('-')[1];
field_arr[id]['top'] = drag.position().top;
field_arr[id]['left'] = drag.position().left;
});
console.log(field_arr);
Iterating over properties of objects is quite easy:
for (var id in field_arr) {
console.log(field_arr[id], field_arr[id]['paId'], 'etc');
}
Add a hasOwnProperty check if your object doesn't inherit from null (var obj = {} needs it, unlike var obj = Object.create(null))
you're storing values with a key string and its wrong because you declared your field_arr as a numerical array (well there's no such thing as associative array in javascript i think).
field_arr[Id] = new Array();
field_arr[Id]['paId']=paId; //this is wrong
You need to create an object to store in values as if they are associated with string keys. But literally they are object properties
redeclare it like this
field_arr[Id] = {}; //you create an object
field_arr[Id]['paId'] = paId; //create an object property named paId and store a value
field_arr[Id].paId = paId; //you can also access property paId like this
EDIT:
but to conform to you current code you can access your indexes using strings by accessing it like a property of an object. (Thanks to Tibos)
var field_arr=[];
...
...
field_arr[Id].paId = paId;

add anonymous object to an object

I know to add a named object to an existing JavaScript object you do this:
var json = {};
json.a = {name:"a"};
But how can you add an object to an existing JavaScript object in a similar fashion without assigning it an associative name, so that it could be accessed by a for() statement. Sorry if I'm being a little vague, I don't know a lot about JavaScript objects.
UPDATE:
I want the end result to look like this:
var json = [{name:'a'}{name:'b'}];
What you have there is not strictly a JSON object. You're using JS object literals rather.
You can do this:
var jsObj = {};
// add a 'name' property
jsObj = { name: 'a'};
var anotherObj = { other: "b" };
// will add 'other' proprty to jsObj
$.extend(jsObj, anotherObj);
// jsObj becomes - {name: 'a', other:'b'}
The JSON representation of above will look like:
var jsonString = "{'name': 'a', 'other':'b'}";
// will give you back jsObj.
var jsonObj = JSON.Parse(jsonString); // eval(jsonString) in older browsers
Note that you cannot have property without a name. This is not valid:
// invalid, will throw error
jsObj = { : 'a'};
Try an array that you push an item on to using
myArrayVar.push(value);
or
myArrayVar[myArrayVar.length] = value;
It makes no sense to have a property of an object without a property name. A "for ... in" loop is a loop over that collection of property names, after all. That is,
for (var k in obj)
will set "k" equal to each of the names of properties in "obj" in turn.
You cannot do this, because a JSON object is a collection of string-value pairs. A value can be an array, and you can push your object into that array, without an associative name.
http://www.json.org/
What you are describing is an array of objects.
var j = [{name:'a'},{name:'b'}];
This has the properties you are looking for. You can operate on it like so:
for(var i in j) {
alert(j[i].name);
}

Categories