jquery array with attribute - javascript

I want to create an array like this in JQuery:
id=1, name="pepe"
How can I do this? I have done this but not working
arr[idx]["id"].push( $(id).text());
arr[idx]["name"].push( $(name).text());
to later access to the id of the array like this:
(arr[0].id)

If your goal is to have an array where each entry in the array has id and name attributes, here's how:
Declare a variable:
var arr;
Create the array:
arr = [];
Add an entry to it which is an object with those properties:
arr.push({
id: $(id).text(), // I assume the `id` in `$(id)` is just placeholder for something
name: $(name).text() // Similarly the `name` in `$(name)`
});
In the above, provided $(id).text() returns "1" and $(name).text() returns "Pepe", you'll end up with an array with one entry, where that one entry is an object with id=1 and name=Pepe.
Then you can access (say) the first of those:
console.log(arr[0].id); // Shows the `id` property of the first object in the array

arr.push({id:1, name:"pepe"});

arr[idx].id = $(id).text();
arr[idx].name = $(name).text();

Related

How to check if array contains objects

I have array, created from json:
var array = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name2","group":"group2","id":"456", ...},
{"name":"name3","group":"group1","id":"789", ...}];
After I get another array:
var array1 = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name4","group":"group1","id":"987", ...}]
I need to push items from second array into first, but how can I check if first array contains objects from second array?
Each object in array contain more property and some of them are created dynamically so I can't check for example by indexOf(). All solutions that I found works only with simple objects like Int. It will be great if I could check by property "id" for example.
Use find first
var newObj = {"name":"name2","group":"group2","id":"456"};
var value = array.find( s => s.id == newObj.id );
Now push if the value is not found
if ( !value )
{
array.push( newObj )
}
(More generic)you can do this one line using following (which will add all object which is not in array).
array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
var array = [{"name":"name1","group":"group1","id":"123"},
{"name":"name2","group":"group2","id":"456" },
{"name":"name3","group":"group1","id":"789"}];
var array1 = [{"name":"name1","group":"group1","id":"123"},
{"name":"name4","group":"group1","id":"987"}];
array=array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
console.log(array);

Update multidimensional array by id?

I have a multi dimensional array like this:
var firstElement = $(this).first();
fielddata = {
number: index,
attributes: [
{ 'label_text': firstElement.text(),
'label_width': firstElement.width(),
'label_height': firstElement.height(),
'label_color': firstElement.css('color')
}
]
}
How can I change one of the values inside the attributes part but by id? so I make 'label_text' a different value?
I do not want to use the index.
You don't have a multidimensional array. You have an object; one of its properties is an array of objects.
In this case, it looks like you want to update label_text in the first (and only) object in the attributes list. If that's correct:
fielddata.attributes[0].label_text = 'whatever';
Will work, as would:
fielddata.attributes[0]['label_text'] = 'whatever';

Setting up an associative array in JavaScript

I have this code:
var mydata = [];
$.each(divs, function(idx, val){
var dID = $(val).attr("id");
mydata[dID] = new Array();
mydata[dID].push({'newproperty':"newvalue"});
});
This gives me results like this:
25465: Array[1]
0: Object
newproperty: "newvalue"
__proto__: Object
length: 1
__proto__: Array[0]
I want it like this:
25465: {
newproperty: "newvalue"
}
Any idea?
I want it like this
You've put in an unnecessary extra level of indirection.
// Create a blank object
var mydata = {};
$.each(divs, function(idx, val){
var dID = $(val).attr("id");
// Add/overwrite a property on that object with the name from the
// variable dID, and the value being a new object with the properties
// shown -- I assume those properties are just examples, since as
// given they're identical on each pass...
mydata[dID] = {'newproperty':"newvalue"};
});
Since you're not using the Array features of arrays, don't use an array, just use an object ({}). Since your goal is to have keys like 25465 refer directly to objects, don't create an array within the array/object, just assign to that key.

Array of email objects in Javascript

I need to use an array of emails whose each record should point to several attributes like To, From, and Subject. I did something like this:
var emailAttr = new Array("to","from","subject");
var emails = new Array(emailAttr);
emails[0].to = "abc1";
emails[1].to = "abc2"; // This line gives exception that emails[1] is undefined
What am i missing and how can i make it work so that I can access elements like emails[i].to ?
var emailAttr = new Array("to","from","subject");
This creates a new array with the values:
0: "to"
1: "from"
2: "subject"
Then
var emails = new Array(emailAttr);
This creates a new array consisting of one value:
0: The array you created in the previous line
Then this:
emails[0].to = "abc1";
adds a new property to the first array:
0: "to"
1: "from"
2: "subject"
to: "abc1"
and then this:
emails[1].to = "abc2";
… tries to do the same to the second item in the emails array, but you haven't assigned an array there so you are trying to set a property on the undefined object which isn't allowed and you get an error.
You probably want to create an array (for your ordered list of email objects) of objects (not arrays, use objects for named values, use arrays for numerically indexed, ordered values), and you need to create a new object for each member.
var emails = [];
emails.push({
to: "abc1",
from: "...",
subject: "..."
});
You can then repeat that to add any many items as you like.
You can edit items in it (but only ones you have already created) using your original syntax:
emails[0].to = "abc1";
NB: Best practise is to use the [] and {} literals to create new arrays and objects, not the constructor functions Array() and Object().
You should make the email an object and push those into an emails array:
// Create emails array
var emails = [];
// Create an email object
var emailObj = {
to: 'mail#mail.com',
from: 'anothermail#mail.com',
subject: 'Hello there'
};
// Add the email to the emails array
emails.push(emailObj);
// Will console log "Hello there"
console.log(emails[0].subject);
You first have to define what the child object is. When you write emails[1].to, you're already trying to access that sub object before it's been defined.
Change it to:
emails = []; // create the main array
emails[0] = {to: 'abc1'}; // define an object and assign it to the main array
emails[1] = {to: 'abc2'};
You have to create an array which consists of objects.
So instead of these lines
var emails = new Array(emailAttr);
emails[0].to = "abc1";
emails[1].to = "abc2";
you can simply write this:
var emails = [{
to: "abc1"
}, {
to: "abc2"
}];

Javascript defining array. "arrayception"

I am trying to create a list of "items" in a canvas game. For example, an array named list. Each element must contain the information about each item. First element will contain something different. I will remove first one with 'shift()' command. Like :
list.shift();
list[0]['name']
list[0]['id']
list[0]['x']
list[0]['y']
list[1]['name']
list[1]['id']
list[1]['x']
list[1]['y']
but i don't know how to define something like this. normally i define arrays like
{"name" : xx, "id" : 5 ... }
but this works like :
list['name']
list['id']
use:
var list = [];
list[0] = {name: 'xx', id: 0, /*etc*/};
list[1] = {name: 'yy', id: 1, /*etc*/};
it creates an array of objects. You can use it like this:
var first = list.shift();
first.name; //=> xx
//or
var first = list[0];
first.name; //=> xx
Note: using {...} (Object literal) creates an Object, not an Array. An array can be created using an Array literal: [...]. Although an object is sometimes said to be an Associative Array, it is not an Array object, so things like {...}.shift() will not work for Objects.
There are no associative arrays in javascript.
so for instance , when you do
var _array = []
_array["field1"] ="value";
you are actually adding a property to the _array object .
_array.field1 = value <=> _array["field1"] ="value";
so if you want to create a collection of objects , do
var collection =[];
var myObject = {"field1":"value1"};
collection.push(myObject);

Categories

Resources