I currently have a problem in deleting entries from an associative array in JS.
I tried this:
myArray['key'] = value;
myArray['key1'] = value1;
...
delete myArray['key'];
But I get following results in my application:
[ undefined, { key1: 'value1', key2: 'value2' }, undefined,
{ key1: 'value1', key2: 'value2' }, undefined, undefined ]
How can I delete the whole entry, key and value? I found the method splice() but I think it uses a different index. I wasn't able to delete the entries I want by passing the key to splice().
It seems you are mixing arrays and objects. Associative arrays should be realized with objects:
myArray = {};
myArray['key'] = value;
myArray['key1'] = value1;
It is a bit confusing though because in your output, the objects don't have key anymore (so it worked), but the array containing those objects as undefined values. I cannot see how
delete myArray['key']; is related to your output and which variable now contains which value (please clarify).
But it looks like you did something like:
var container = new Array(6);
container[1] = myArray;
container[3] = myArray;
This will initialize the array with 6 undefined values (sort of) and then set the second and forth value to something else.
If you want to use that "array" as associative array, you should declare it as object too:
var container = {};
Please post more code if you need a better answer.
Update: Yes, you should declare displayedWidgets as object:
var widgets = {
displayedWidgets: {},
clear: function() {
this.displayedWidgets = {};
},
add: function(widget) {
this.displayedWidgets[widget.id] = widget;
},
addArray: function(newWidgets) {
// note that `each` is only available in newer browsers,
// just loop over the array
for(var i = newWidgets.length; i--; ) {
this.add(newWidgets[i]);
}
},
remove: function(widgetId) {
if (widgetId in this.displayedWidgets) {
delete this.displayedWidgets[widgetId];
}
}
};
Related
Let's say I have two arrays which are returned in a response from a REST call. For simplification I defined them hard-coded as keys and subKeys in the following example code.
From these arrays I'd like to create a nested object which, when outputted as a JSON string, looks like this:
Target JSON
{
"key1": {
"subKey1": "someValue"
},
"key2": {
"subKey2": "someValue"
},
"key3": {
"subKey3": "someValue"
}
}
Code sample
var keys = ["key1", "key2", "key3"]; // These come from a REST response
var subKeys = ["subKey1", "subKey2", "subKey3"]; // These come from a REST response
var targetObj = {}
for (const key in keys) {
targetObj[key] = {}
for (const subKey in subKeys) {
targetObj[key][subKey] = "someValue";
}
}
console.log(JSON.stringify(targetObj, null, 2));
While this gives me the correct behavior in my application I have the impression that there might be simpler approaches to achieve the same result, either in "vanilla" JavaScript or ES6? What bothers me here is that I define an empty object in each run of the for loop.
Your code does not produce the example output you said you want. It will put all 3 subkeys under each key, not one per key. Also you end up with numeric keys, not the key names.
var keys = ["key1", "key2", "key3"]; // These come from a REST response
var subKeys = ["subKey1", "subKey2", "subKey3"]; // These come from a REST response
var targetObj = {}
for (let i=0; i<keys.length; i++) {
const key = keys[i];
targetObj[key] = { [subKeys[i]]: "someValue" };
}
console.log(JSON.stringify(targetObj, null, 2));
First you were using "in" instead of "of" in the for-loop, and secondly you were not using the same index to find the subkey.
To avoid creating an empty object you can use this syntax:
{ [variable]: "value" }
This creates the object with the variable value as the key, and a string as the value. Putting the variable name in square brackets tells it to use the variable value rather than its name. Saying { variable: "value" } wouldn't work because the key would be "variable" not the value of variable.
Just use Array.prototype.reduce method:
const keys = ["key1", "key2", "key3"];
const subKeys = ["subKey1", "subKey2", "subKey3"];
const result = keys.reduce((acc, key, index) =>
({ ...acc, [key]: { [subKeys[index]]: 'someValue' } })
, {});
Note, this works only if keys and subKeys arrays are synced and their indexes are consistent with each other.
I have an array, inside this I have objects. I need to work with this and need to access to the object data.
Here is a sample of this array:
var result <-
(16)array […]
0:object {…}"myobjectname1": {…} style_name: "border-top-right-radius"
style_unit: "px"
style_value: "0"
1:object {…}"myobjectname2": {…} style_name: "border-bottom-right-radius"
style_unit: "px"
style_value: "0"
2:object { "myobjectname3": {…} }
3:object { "myobjectname4": {…} }
4:object { "myobjectname5": {…} }
...
I want to access directly to the different objects by the objectname
Example alert("result.myobjectname1.style_name");
It seem that this could not work, because I don't access the array by the index in this case [0]!?
I don't know this index, it could be different every time.
Is there a way, to directly access the objects by the objectname or in which way, I have to create a array/object that it works?
In php I will do it with a simple array, in JavaScript its not possible because my index is alphanumeric.
UPDATE
This is the way i create the datas in a each-loop
var match=new Array();
each(...)
{
...
var r = null;
r={ [myobjectname_from_variable] : { 'style_name': res_stylename,
'style_value': res_stylevalue,
'style_unit' : elem_styleunit} };
match.push(r);
...
}
Important: The value of myobjectname_from_variable is the same as res_stylename and it contains something like "border-top-right-radius"
Here we have to think about, how i can call this in javascript. For example
object.border-top-right-radius.style_value
wont breack and returns a error of undefined "right"...
You could build an object with all objects of the array. Then take the key of the wanted object for access.
var array = [
{ foo: { id: 1, name: 'foo' } },
{ bar: { id: 2, name: 'bar' } },
{ baz: { id: 3, name: 'baz' } }
],
object = Object.assign(...array);
console.log(object.foo.id);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
For a faster access via a key, you could build your object with a defined object, like
var data = {};
And in the loop, you could assign the value object like this with a property accessor
// inside of the loop
data[myobjectname_from_variable] = {
style_name: res_stylename,
style_value: res_stylevalue,
style_unit: elem_styleunit
};
Your best bet is to iterate the array and then call the index of each iteration. There's also an array method called .forEach that wraps this up for you.
var yourArray = []; // contains the array of objects you mentioned
yourArray.forEach(object => {
const key = Object.keys(object)[0];
alert(object[key].style_name);
})
Update
Your main issue is the use of hyphens in your keys. If you want to index an object like that then you'll need to reference the keys as strings.
const obj = {'border-top-right-radius':'style_value'};
const test = obj['border-top-right-radius'];
console.log(test); // this logs 'style_value '
const other = obj.border-top-right-radius;
// This will throw that 'right' is undefined.
If you want that format then change your hyphens to underscores. With underscores, there's no issue directly referencing them as you desire. You can easily remap to the hyphenated string later for what you're doing with .replace
const underscoreReplacement = 'border_top_right_radius';
const actualSheetValue = underscoreReplacementreplace(/_/g, '-');
console.log(actualSheetValue); // logs 'border-top-right-radius'
I have some problem with sorting items inside object. So I have something like this:
var someObject = {
'type1': 'abc',
'type2': 'gty',
'type3': 'qwe',
'type4': 'bbvdd',
'type5': 'zxczvdf'
};
I want to sort someObject by value, and this is where I have problem.
I have sorting function that should return key/value pairs sorted by value:
function SortObject(passedObject) {
var values = [];
var sorted_obj = {};
for (var key in passedObject) {
if (passedObject.hasOwnProperty(key)) {
values.push(passedObject[key]);
}
}
// sort keys
values.sort();
// create new object based on Sorted Keys
jQuery.each(values, function (i, value) {
var key = GetKey(passedObject, value);
sorted_obj[key] = value;
});
return sorted_obj;
}
and function to get key:
function GetKey(someObject, value) {
for (var key in someObject) {
if (someObject[key] === value) {
return key;
}
}
}
The problem is in last part when creating new, returning object - it's sorted by key again. Why? And this is specific situation when i have to operate on object NOT on array (yes I know that would be easier...)
Does anyone know how to sort items in object?
Plain objects don't have order at all. Arrays -that are a special types of objects- have.
The most close thing that you can have is an array with the object values sorted . Something like, for example:
_valuesOfAnObjectSorted = Object.keys(object).map(function(k){ return object[k]; }).sort();
You have two possibilities:
Refactor your object into an array
Something like this:
var myObj = [
['type1', 'abc'],
['type2', 'gty'],
...
];
Or even better, since using it somewhere would not rely on array positions but full named keys:
var myObj = [
{name: 'type1', val:'abc'},
{name: 'type2', val:'gty'},
...
];
Use your object with an auxiliar array
Wherever you want to use your object ordered by the keys, you can extract the keys as an array, order it and traverse it to access the object
var ordKeys = Object.keys(myObj).sort(); // pass inside a function if you want specific order
var key;
for (var i = 0, len = ordKeys.length; i < len; i +=1) {
key = ordKeys[i]
alert(key + " - " + myObj[key]);
}
Combination of both of them
If the object is not constructed by you, but comes from somewhere else, you can use the second option approach to construct an array of objects as in the first option. That would let you use your array anywhere with perfect order.
EDIT
You might want to check the library underscore.js. There you have extremely useful methods that could do the trick pretty easily. Probably the method _.pairs with some mapping would do all the work in one statement.
I have the following requirement. I have a pair of integers which is to act as keys and another pair of integers which should act as values. That is:
obj[{key1:12,key2:23}]=[2,3];
obj[{key1:12,key2:22}]=[4,3];
obj[{key1:34,key2:12}]=[4,33];
Also finally when the population of this list is over, I would like to sequentially access the elements of the object/array.
Now it is my understanding that for such arrays which take an object as key, they are known as associative arrays and Javascript doesn't support them..
The following will be the operations I will perform on this structure :
Insertion: I will have keys like (2,3) or (2,4) which I would like to insert into the array with a new keyvalue pair such as [1,2],
Lookup : I may have a key pair like (2,3) which is already inserted into this array and I would like to get it back so that I can modify it.
That is something like:
if(obj[{key1:2,key2:3}])
obj[{key1:2,key2:3}]=[2,5];
else
obj[{key1:2,key2:3}]=[2,-1];
Any suggestions as to how I can implement this in Javascript?
EDIT: These are the two things I tried:
First I made it as an array of objects. This approach didn't work because from looking around, I knew that in such cases, Javascript will call the toString method to get the string equivalent of the object which it will then use an index.
Second, I tried to do an object with object keys containing sub-objects. Something along the lines of this answer: Answer. However I am not sure how to get sequential access to all the elements after I am done with the insertion phase.
You're probably not going to like this much, but it'll at least give you a stable key:
obj[JSON.stringify({key1:12,key2:23})]=[2,3];
So, the big problem is that in an object the 'key' (really, the 'property') must be a string, or be able to be stringified. In your examples, {key1:12,key2:23} will always be stringified to [object Object]. So you'll never get a unique key. The only way to get that unique key is to really serialize it, such as by using the JSON.stringify method.
Note that on IE8 I think you have to include a JSON class.
Here is an object oriented way to do it:
// Constructor
function AssociativeArray() {
this.length = 0;
}
// Add or set value
AssociativeArray.prototype.set = function(key, value) {
key = key.key1+'|'+key.key2;
if(!this[key]) {
this.length++;
}
this[key] = value;
};
// Lookup
AssociativeArray.prototype.get = function(key) {
return this[key.key1+'|'+key.key2];
};
AssociativeArray.prototype.toString = function() {
var k, arr = [];
for(k in this) {
if(this.hasOwnProperty(k) && k !== 'length') {
arr.push(this[k]);
}
}
return arr;
};
// Create Associative Array
var arr = new AssociativeArray();
// empty array
console.log(arr.toString(), 'length='+arr.length); // [] length=0
// add value
arr.set({key1:1, key2:2}, [1,1]);
console.log(arr.toString(), 'length='+arr.length); // [[1,1]] length=1
// add value
arr.set({key1:2, key2:1}, [2,2]);
console.log(arr.toString(), 'length='+arr.length); // [[1,1], [2,2]] length=2
// set value
arr.set({key1:2, key2:1}, [3,3]);
console.log(arr.toString(), 'length='+arr.length); // [[1,1], [3,3]] length=2
// lookup and set
if(arr.get({key1:2, key2:3})) {
arr.set({key1:2, key2:3}, [2,5]);
} else {
arr.set({key1:2, key2:3}, [2,-1]);
}
console.log(arr.toString(), 'length='+arr.length); // [[1, 1], [3, 3], [2, -1]] length=3
Fiddle here: http://jsbin.com/ohOwala/3/edit
You could use a bidimensional array
var arr = [];
arr[2] = [];
arr[2][3] = [1, 2];
Or you could use an object and access the pairs using the object properties names
obj = {
_2_3: [1, 2],
_2_1: [4, 1],
_1_2: [3, 2]
};
and access them like this obj["_2_3"] or this obj._2_3
or maybe you could nest em
obj = {
_1: {
_2: [2,1]
}
};
so you could access them like this obj["_1"]["_2"]
or maybe this
obj = {
1: {
2: [2,1]
}
};
But you will be forced to use associatve array notation obj["1"]["2"]
and as far as i know using the associative array like way for accessing objects properties isnt a good practice
I asked where the objects {key1:2,key3:2} came from because if you have control over it you can implement a toString method for those types that will take care of the Object to string conversion so it can be used as a property name.
//define keypair object type
var MyKeyPair = function(key1,key2){
this.key1=key1;
this.key2=key2;
};
//define tostring for this type
// later obj[aKeyPairInstance] will
// invoke the toString method
// if you don't do this then [Object object]
// would be returned for toString
MyKeyPair.prototype.toString=function(){
//since you know there is only going to be key1 and key2
// you could just:
// return this.key1+":"+this.key2;
//Here follows a more general approach but it'll cost
// you more cpu time, if working with very large amounts
// of data use the shorter version.
var ret=[];
for(thing in this){
if(this.hasOwnProperty(thing)){
ret.push(thing);
ret.push(":");
ret.push(this[thing]);
ret.push(",");
}
}
return ret.join("");
};
// make a bunch of keyPair objects
var keys = [
new MyKeyPair(21,33),
new MyKeyPair(22,34),
new MyKeyPair(23,35),
new MyKeyPair(24,36)
];
//create an object and give it properties
// based on the tostring value of the keypairs
var obj={};
for(var i = 0,len=keys.length;i<len;i++){
obj[keys[i]]=[keys[i].key1,keys[i].key2];
};
console.log(obj);//<=this would not log any usefull info in IE
//Use Chrome, Firefox, Opera or any other browser instead
I want to map the keys of a large array into another key while removing the original key using Underscore.js' map() function.
large_array = _.map(data, function(element) {
element.b = element.a;
delete element.a;
return element;
});
console.log(large_array) // Returns an array with length == 0
Why would large_array have a length of zero?
I feel like I'm using the delete statement incorrrectly but I'm not sure.
Edit:
I may be abstracting this code too much, since simple runs seem to be working just fine.
The original data array is response from the FB.api('/me/friends', function(response) {...}
More specifically, it is an array of objects such as
{id: "12345", name: "Bubba Watson"}
As this is a response from Facebook, each object is guaranteed to have the 'id' attribute
The actual code is changing the the 'id' property to a 'facebook_id' property.
FB.api('/me/friends', function(response) {
console.log(response.data); // Returns 600+ Array of Bubba Watson like objects, each with an id.
large_array = _.map(response.data, function(element) {
element.facebook_id = element.id;
delete element.id;
return element;
});
console.log(large_array); // Mysteriously Returns: {length: 0, __proto__: Array[0]}
}
You're using delete correctly, however you may need to make sure:
data is indeed type Array and there are elements in data array
each element in the data array has property named a
Your code works for me: http://jsfiddle.net/EJTgx/
var data = [
{ a: 10 },
{ a: 20 },
{ a: 30 }
];
var large_array = _.map(data, function(element) {
element.b = element.a;
delete element.a;
return element;
});
console.log(large_array.length); // Returns 3