Object values to array but with same reference - javascript

I have an object with dynamic properties. Each of these properties are removed and added based on some events. I want to have a function or property in this object which can return the array of values but having the same reference all the time. Whats the best way to do it?
For e.g if current state of the object is
var obj = {"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} }
var values = obj.someFunction()
values should be [{ 'name' : 'dark'}]
if current state of obj is
{"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} ,
"f44abc3bb1dad3cd20e97e6a21416830": { 'name' : 'magic'}}
values should be [{ 'name' : 'dark'},{ 'name' : 'magic'}]
The reference of the array and the properties should never change (unless they are deleted).

How about this? It maintains the same array. If you want, you could also mix it in with the object, but would have to add a guard to not also add the function to the values.
var values = someFunction(obj, values);
function someFunction(obj, values) {
values = values || [];
values.length = 0;
for(var key in obj) {
values.push(obj[key]);
}
return values;
}
By the way, clearing the array by setting its length to 0 was gleaned from this post.

My might create a 'meta'-object that stores a reference to the original object and can return the values:
var Values = function(obj) {
this.getValues = function() {
var values = [];
for(i in obj)
values.push(obj[i]);
return values;
};
}
var original = {"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} ,
"f44abc3bb1dad3cd20e97e6a21416830": { 'name' : 'magic'}};
var vals = new Values(original);
var values = vals.getValues();

Given that you seem to be generating the array within "someFunction" (seeing the code of the function and how you attach it to the object would help), you'll need to keep an instance of an array and empty/refill it rather than create a new one. It could be a member of your object (obj.currentItems) or within a closure (depending on how you create it), and it could be updated as you change its properties or on demand within someFunction.
I'll update my answer if you provide more specific code.

Related

how can I add this object in an array?

How can I add {[]} in an array?
#CertainPerformance is correct. You have to have an associated property if you want to have objects.
var a = [ { propertyName : [] } ]
then you can access that array like this :
a[0].propertyName or a[0]['propertyName']
And you can have multiple values inside the object too :
var a = [
{
propertyName_1 : [],
propertyName_2 : "",
propertyName_3 : 3,
}
];
var a = [{}] // no problem, you are assigning an empty object `{}` as first element of array
var a = [[]] // no problem, you are assigning an empty array `[]` as first element of array
var a = [{[]}] // Not working because you're assigning empty array into object
//object needs key to store value
var a = {[]} //Not ok <<======== have you ever see var a = { 1, 2, 3} ?
Please refer to documentation:
An object is a collection of properties, and a property is an association between a name (or key) and a value.

Assigning a javascript object with and object inside an array

I am just curious about this.
Let's say I have an array of objects and I create 1 object, lets name the array of objects items and the object item.
I want to get a particular item in my array of items by using the following code:
//gets an item base on ID
function get_item(td){
var item = undefined;
$.each(items, function(i, val) {
if(val.item_id == td){
item = val;
}
});
return item;
}
The get_item() basically gets an object matched with the supplied id.
So my question is this. What if I changed the properties of item will it also changed the properties of an object associated with it within the array?
Thank you very much!
What if I changed the properties of item will it also changed the properties of an object associated with it within the array?
Yes.
Objects are not copied. Instead, references to the objects are passed around. Simplest example:
var a = [];
var b = a;
b.push(1);
console.log(a); // logs [1]
Many object-oriented programming languages work like this.
The value of the object inside the array will also change because it's a reference. If you want more information I highly recommend reading Objects and Prototypes.
If you don't want it to change then you should use something like lodash's _.clone() function.
Also you could use filter to get the object:
function get_item(td){
return items.filter(function(item) {
return item.id === td;
})[0];
}
You can update you function to:
var data= array();
function get_item(propertyValue, propertyName){
var retval;
for(var i = 0; i < data.length; i++){
if(data[i][propertyName]==propertyValue){
retval = data[i];
break;
}
}
return retval;
}
Use it
var item1 = get_item(1,"id");
var item2 = get_item("john","name");

Javascript add data in multidimesional array

I'm trying to understand how to add a value into my array. It is multidimensional:
var eventcontent = {
'2015-05-02' : [{'title':'somethingtitle1','content':'somethingcontent1','something':'something1'},{'title':'somethingtitle2','content':'somethingcontent2','something':'something2'}],
'2015-05-07' : [{'title':'somethingtitle7','content':'somethingcontent7','something':'something7'}],
}
How can I achieve adding the following data into the '2015-05-02'?
{'title':'somethingtitle3','content':'somethingcontent3','something':'something3'}
thanks for your help
eventcontent is object. Firstly you have to gain access to array stored under 2015-05-02 key. 2015-05-02 is not valid property identifier so you can't access it via
var array = eventcontent.2015-05-02 // SyntaxError
instead you have to use bracket notation
var array = eventcontent['2015-05-02'];
then you can for example push your data to the array
var data = {'title':'somethingtitle3','content':'somethingcontent3','something':'something3'};
var array = eventcontent['2015-05-02'];
array.push(data);
Edit:
Probably you should also check if array actually exist so your code becomes:
var data = {'title':'somethingtitle3','content':'somethingcontent3','something':'something3'};
var array = eventcontent['2015-05-02'];
if (array === undefined) // check if it is undefined and if so...
array = eventcontent['2015-05-02'] = []; // make empty array and assign it to eventcontent under '2015-05-02' key
}
array.push(data);

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;

Jquery fill object like array

This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).

Categories