Accessing Value in Array Object with Generic Variable for Key - javascript

I recognize that I can access the value of an object within an array by passing in the key name, like so:
const batchNumValue = batchNumber[0]['MAX(batch_number) + 1'];
In my case I know the array will always contain exactly one object, with a single key/value pair, like so:
[{ 'MAX(batch_number) + 1' : 234 }]
That being the case, my question is, is there a way I can pass in a variable representing whatever that key name happens to be? Or does one have to always explicitly pass the key name, even in a situation like this?

You could get the values from the object and take the first item.
const
data = [{ 'MAX(batch_number) + 1' : 234 }],
value = Object.values(data[0])[0];
console.log(value);

Related

Javascript Nested Objects/Arrays Code Reduction Problem

I have an object for a collection of video data called "CollectionData". It has 3 key/value pairs:
collectionData.title - a simple string value
collectionData.seriesData - an array
collectionData.progressData - an array
Each of the 2 array values are objects:
collectionData.seriesData[x].title
collectionData.seriesData[x].year
collectionData.seriesData[x].length
collectionData.seriesData[x].synopsis
collectionData.progressData[x].currentTime
collectionData.progressData[x].progress
To save from having to type out collectionData.seriesData[x] or collectionData.progressData[x] every time to access the key's values I use a "pointer" into the object:
var p = collectionData.progressData[x];
I can then access the values of the keys by using p.currentTime, etc.
This works well if I want to replace a single key's value, i.e. p.currentTime = 25. However, if I want to replace the entire object's value, i.e. p = {currentTime:25,progress=10} the assignment operator does not evaluate the value of the variable p as a pointer into the object but as the pointer itself, therefore the object's value is not updated.
Is there a way to force the assignment operator to evaluate the variable p as a pointer or will I have to revert back to the full object name collectionData.progressData[x]={currentTime:25,progress=10}?
You could take Object.assign and the new data which update the object.
const
data = [{ currentTime: 1, progress: 1 }],
p = data[0];
Object.assign(p, { currentTime: 25, progress: 10 });
console.log(data);

JavaScript : Printing Dynamic value/data

This is sample JSON I got {"valueofa" : 1234}.To print the value it is something like body.valueofa. However, this valueofa can be anything like apple or something else. So to parse that I object I had tried with ${body}.${value} which isn't working and it's shouldn't be. How can I set the variable with body. So that I can parse the body whatever the value is.
If your object always contains only one key value pair like shown in the question, and you don't care about the key, you can just use Object.values()
console.log(Object.values({"valueofa" : 1234})[0]);
console.log(Object.values({"apple" : 1234})[0]);
The same is true for objects holding multiple key value pairs, Object.values() will return an array of all the values in your object if you omit accessing the first element with [0]
You can access a value of JSON using square brackets.
var value = "valueofa";
body[value];

Best way to find index of exact same object in object Array (key is dynamic)

Let's say I have dynamically loaded object each time with different properties and an array of objects of that type:
var obj = {name: someValue, key: someValue2};
var objArray = [{name: someValue, key: someValue2},{name: someValue, key: someValue3}];
I want to find index of objArray which contains the obj. Some elements of objArray can have the same name property but different key property so searching through obj.name is not an option. So far I came up with this solution:
var keys = [];
_.forEach(Object.keys(obj), function(key) {
keys.push(key, obj[key])
});
var index = _.findIndex(objArray, keys);
This works fine and all but I am looking for something with better performance because this objArray can be very large.
So the question is: Is there a better way to find index of exact same object in object Array?
Update:
I forgot to mention that the names of the keys are not specified and can vary each time.
Use Array.prototype.findIndex(), this works only if you know in advance the property you want to check and hard code the rules in the callback for .findIndex().
An example:
var obj = {
name: 'someValue',
key: 'someValue3'
};
var objArray = [{
name: 'someValue',
key: 'someValue2'
}, {
name: 'someValue',
key: 'someValue3'
}];
var index = objArray.findIndex(function(item, index) {
return (item.name === obj.name) && (item.key === obj.key) ? true : false;
});
console.log('index is: ' + index);
This below it is another approach, basically it takes a JavaScript value (your initial object) and convert to a JSON string, and it uses that string to search within your array. The script works without any recursions, with any number of nested properties for your objects. The order of your property is important in this script, as the conversion to string take it in consideration.
Regarding "best way" is difficult to answer, depending what are your parameters for best way. If you consider performance, you should consider benchmarking your scripts and do test with some real data.
var obj = {
name: 'someValue',
key: 'someValue2'
},
objArray = [{
name: 'someValue',
key: 'someValue2'
}, {
name: 'someValue',
key: 'someValue3'
}];
var str = JSON.stringify(obj),
index = objArray.findIndex(function(item, index) {
return str === JSON.stringify(item) ;
});
console.log('index is: ' + index);
I can think of 2 approaches for doing this:
1.) What would speed up the process (especially if you got large array and large objects) is to create some kind of unique key for every object and map it to let's say property called: hash. If you wanna keep it vanilla, the best way to do that might be using the String.hashCode() method.
Iterate trough object OWN (check hasOwnProperty) properties and concat into single string both property name and then ### and then value and then %%% in between.
Then enhance your object with property hash like:
myObj.hash = String.hashCode(StringOfNamesAndValues);
Now iterate trough your array using for, and compare obj.hash to objArray[index].hash
Once they match you fond your object, store the index :)
If your object and one in the array don't have to be EXACTLY the same object but only a subset needs to be same. Instead using all property names in hash generation, use only the names and values of properties you wanna to be same. Compare hashes made in that way - voila!
2.) More brutish way would be to make object equal function that takes 2 objects and compares all the properties and values of respective properties. Now iterate trough array using that function. Pass your object and array object as parameters. If it returns that comparison is true, store index.
The bigger the objects are the slower this works.The bigger array is the slower this works. The more time you search for same objects slower this works (you compare every time instead making hash once).
Also, if you are having a very large set of object, and search often but add or remove to it sparsely, consider ordering the array in order considering hash values. Then use binary tree search for that hash to find appropriate object instead iterating from start to end each time.

JavaScript Array Issue with data['sax']

I have a confusion of what this array can hold. Also, I want to know how it assigns the values to the variable set.
Can someone give me an example of data['sax'] please and explain me the loop below?
for(var x = 0; x < data['sax'].length; x++){
var set = data['sax'][x];
Then what does this mean ?
id : set.saxID,
name : set.symbol
What you have here is an array that is being looped through. data['sax'] will be something along the lines of the following:
var data = {
sax: [
{
saxID: 1,
symbol: 1
},
{
saxID: 2,
symbol: 2
}
]
}
As you can see in the example above, sax is an array which contains multiple objects. What happens when you loop over it, is that it accesses one of the objects inside the array. So data['sax'][0] will give you the object with saxID: 1.
Using the variable set to temporarily store the data in; you can access the data of data['sax'][0] as set. So data['sax'][0].saxID becomes set.saxID. It is somewhat of a shorthand version of accessing the data.
What happens with id: set.saxID, is that the values get assigned to a new object. Which will be something like the following.
var newSax = {
id: set.saxID
}
You are basically transferring data from one object to another.
Explaining the code
var set = data['sax'][x];
Here you are creating a variable called set and assigning it a value from data['sax'][x].
data['sax'] this might look like a array But Its Not, to access value of a array we use index but here its a string. This is another way of accessig a property value of a object. So data is a object with one of its property being sax. That means
data = {sax: somevalue};
Now we have,
data['sax'][x] So as you know data['sax'] is a object and then this [x] , here x is not a string its a variable and it holds the Number value (0,1,2,3...) , it means your data['sax'] value is a array since we are accessing from index.
So from the above analysis your data['sax'] will be in this format.
Array
data = { sax : ["someValue","someValue"]}
So variable set will be
var set = "someValue"; // if x = 0, as in the first loop
Now coming to the code
id : set.saxID,
name : set.symbol
set.saxID this is used if the set is an object. In Jquery to retrieve the value of a property in the object you use the . operator with property name (or by the property name as seen above). So the code means set is a object with two properties saxID and symbol. So your set object will be like
set = { saxID: 123, symbol = "TEST"}
That also means that your data value be
data = { sax : [{saxID: 123, symbol = "TEST"},{saxID: 123, symbol = "TEST"}]}
Let me know if I was clear

How to use Meteor.users.update to inc a variable in a case specific object?

I need to inc a variable within the case specific object in an array in the profile object in the users object/mongo collection. The case specific object's name will equal a local variable, and the I want to inc the variable num by 1. What would the syntext for this look like?
I don't know exactly what your model looks like but here is an example that may help you.
Test=new Mongo.Collection(null);
var id=Test.insert({
hashtags:[{
tag:"meteor",
count:2
},{
tag:"javascript",
count:5
}]
});
var tag="meteor";
Test.update({
_id:id,
"hashtags.tag":tag
},{
$inc:{
"hashtags.$.count":1
}
});
console.log(Test.findOne());
In this example, we specify in the query that we're interested in updating only the array item whose tag matches our local variable, then we use mongodb $ positional operator to increase the item count property accordingly.

Categories

Resources