JavaScript Object declaration by combining two different keys - javascript

I'm not sure if it's possible or not. So here I'm looking for an answer.
Is there any way to declare an object like:
var objectName = {
key1 : 'value1',
key2,key3 : 'value2;
}
I'm trying to combine key2 and key3 together.

If you don't want to assign the values like Patric Roberts says, create an array of keys and set the same value to those keys like so:
var obj = {};
obj['key1'] = 1;
// Array of keys
var arrayOfKeys = ['key2','key3','key4'];
// Common value for keys in array
var val = 2;
// Iterate the array
for(var k in arrayOfKeys) {
obj[arrayOfKeys[k]] = val;
}
console.log(obj);
You can also check this answer

You could use a slightly different approach, which will work on primitive values, too, by adding an object for keeping the same reference to different keys in the array. For example, you have a value object, like
temp = {
value: 42
}
and an array, like
object = {
key2: temp,
key3: temp
}
then you can use the keys independently for the value of the referenced object.
To change the value, you need to address it with
object.key2.value = 2000;
console.log(object.key3.value); // 2000

Related

Array of objects: accessing an object's value without iterating through the array

I have an array of similarly structured objects:
var my_arr = [{property1: some_value, property2: another_value}, {}, {}, ...];
Currently, to find the object containing a target value, I iterate through each element of the array:
var my_obj, target_value;
for (let obj_in_arr of my_arr) {
if (obj_in_arr.property1 === target_value) {
my_obj = obj_in_arr;
break;
}
}
Is there a faster way? How can I access the object with the target value directly, without resorting to iteration?
If you prepopulate a new Map all subsequent searches will be in O(1)
const objMap = new Map()
for (let obj of my_arr) {
objMap.set(obj.property1, obj)
}
function getObject(target, map) {
return map.get(target)
}
I think you need to iterate the array anyway, but you can try _.findIndex of underscore.js
http://underscorejs.org/#findIndex
If you only need to find a value once, then iteration is really the only way.
If you will want to find many values in the array, you could create an object keyed on your target property to serve as a lookup table:
var lookup = {};
for (var i = 0; i < my_arr.length; i++) {
lookup[my_arr[i].property1] = my_arr[i];
}
That front loads some work, but could save you time ultimately if you have many lookups to make.
Lookups would be as simple as:
my_obj = lookup[target_value];
If you have access to es2015 you could make your lookup table generation a little more concise:
const lookup = my_arr.reduce((m, v) => (m[v.property1] = v, m), {});
this will still iterate through the array but you could use the native js find function.
const objArray = [{ val: 1}, { val: 2}];
const targetObj = objArray.find((obj) => obj.val == 2 ) // { val: 2}

Object map Javascript

I have a object map in JavaScript and I have to read it.
The object map is:
network[0]
Object {dpi: "user2"}
I have used this to read the key:
demp=Object.keys(network[0]);
sourceNodeFirewall = demp[0];
But I'm not able to read the value ("user2").
I know that I can do this:
network[0].dpi
in order to have user2, but during a for cycle I have no idea to do it, in addition that the key can change in any value.
I cannot put the real code because it is very complicate but an simple example is:
The object is set in this way:
var network = {};
network[$("#0B").val()] = $("#0BB").val();
Where I have a key and I value.
After that I wish to get the value and the key.
demp stores all key of the object, You need to access the property from the network[0] object.
var network = [{dpi: "user2"}];
demp = Object.keys(network[0]);
console.log(network[0][demp[0]]);
You can access an object's properties by indexing into it with square brackets:
var network = [{dpi: "user2"}];
console.log(network[0]);
var demp = Object.keys(network[0]);
var sourceNodeFirewall = demp[0];
var propValue = network[0][demp[0]];
console.log(propValue);
In a for loop you need to iterate over each key in the map, and to access the value just lookup the map with that key as the index.
var network = {
dpi: "user2"
}
for (var key in network) {
console.log(network[key]);
}
As you referred to a for loop, here what I think you are looking for:
const obj = {
dpi: "user2"
};
for(key in obj){
console.log(obj[key]);
}
Or maybe using a forEach:
const obj = {
dpi: "user2"
};
Object.keys(obj).forEach(
key => console.log(obj[key])
)

Can Javascript objects be accessed like arrays?

Assuming an object is initialized as following:
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
Can I retrieve key values like this?
var retrKey1 = myObj[0];
var retrKey2 = myObj[1];
var retrKey3 = myObj[2];
...
The issue I am trying to solve is that I need to pick random key values from this object. Generating a random number is not an issue, but:
How can I retrieve the number of keys in the object/map?
Can I retrieve the key values using a integer index like in arrays?
If not, what are my options?
The Object.keys method returns an array of object properties. You can index the array with numbers then.
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
var keys = Object.keys(myObj);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
No, because there's no ordering among property keys. If you want ordered keys, you need to work with an array.
You could define a structure like this :
var myObj = [
{key:"key1", val:"val1"},
...
];

Randomly select enumerable property of object in Javascript

Given a dictionary-like object in Javascript such as {a:1, b:-2, c:42}, is there a simple way to randomly choose a property?
In the above example, I would like to have a function that would return a, b or c randomly.
The solution I've come up with is like the following:
var proplist = []
forEach(property in foo) {
if(propertyIsEnumerable(foo[property]) {
proplist.push(property);
}
}
var n = proplist.length;
// randomly choose property (randInt(n) returns a random integer in [0,n))
proplist[randInt(n)];
Is there a more idiomatic way to do this?
Use Object.keys (or even Object.getOwnPropertyNames) to get a list of all properties. Then, select a random property by multiplying Math.random() with the length of the list, floored.
var propList = {}; //...
var tmpList = Object.keys(propList);
var randomPropertyName = tmpList[ Math.floor(Math.random()*tmpList.length) ];
var propertyValue = propList[randomPropertyName];
This can be quite idiomatic with underscore.js:
randomProp = _.shuffle(_.keys(obj))[0]
Edit: actually, one should use _.sample for that.
Or if you want to write a reusable function for this, you could do
const randomFrom = list => list[Math.floor(list.length * Math.random())];
const randomProp = obj => randomFrom(Object.keys(obj));
randomProp(propList); //=> one of the keys of propList
This will return undefined if your object has no properties, but that's probably the best we could do in any case.

Javascript Arrays - Alternative to arr[arr.indexOf()]?

var arr = [foo,bar,xyz];
arr[arr.indexOf('bar')] = true;
Is there an easier way to do this in JS?
You could just use objects.
var obj = {foo: true, baz: false, xyz: true};
obj.baz = true;
All values in that array are already undefined. (You edited your post) I don't know why you are complaining about 2 whole lines of code though.
Short answer no, you can't access an index of an array without knowing the index.
One IE safe way would be to create a prototyped function which lets you set it easily:
Array.prototype.setKeysWithValue = function(keyValue,newValue)
{
var i;
for (i in this)
{
if (this[i] === keyValue)
this[i] = newValue;
}
}
This can then be used like:
var arr = ['foo','bar','xyz'];
arr.setKeysWithValue('bar',true);
In your example you would really only be replacing "bar" with true; your resultant array would look like [foo, true, xyz].
I think it's assumed that what you're asking for is an alternative to having one set of arrays for keys and one set of arrays for values, of which there is no better way.
However, you can use an associative array, or objects, to maintain a key value pair.
var f = false, t = true;
// associative array
var arr = new Array();
arr["foo"] = arr["bar"] = arr["foobar"] = f;
arr["bar"] = t;
// object
var obj;
obj = {"foo":f, "bar":f, "foobar":f};
obj["bar"] = t;
// the difference is seen when you set arr[0]=t and obj[0]=t
// the array still maintains it's array class, while the object
// is still a true object
It's important to realize a few things if you use this method:
the array.length no longer applies, as it only accounts arrays by numerical index, it does not count array properties, which is what the keys in an associative array are
looping through keys/properties becomes a little more difficult since the Array object should have some native properties/methods
you may only have one key/value pair. The array structure you listed would be allowed to have [foo, bar, xyz, bar, foobar, foo], where the index should return the first occurrence in anything browser other than IE<=8
One other way to do what you were specifically asking is:
Array.prototype.replace = function(from,to){ this[this.indexOf(from)]=to; };
Array.prototype.replaceAll = function(from,to){ while(this.indexOf(from)>=0){this[this.indexOf(from)]=to;} };
var arr = new Array();
arr=[ "foo", "bar", "foobar", "foo" ];
arr.replace("bar",true); // [ "foo", true, "foobar", "foo" ]
arr.replaceAll("foo",false); // [ false, true, "foobar", false ]

Categories