Creating a hash of data JS - javascript

I have some data set represented as array, which i want to put in an object as property. I want each property to be accessible by generated key. Number and type of elements in array is unknown. I want it to look something like that:
// array - array on unknown data
let object = {};
object[createUniqueKey(array)] = array;
// and later i want to use it the same way
console.log(object[createUniqueKey(array)])
Hope i've described well, thanks for help in advance

The easiest way to create a unique key to avoid having your object's data overwritten is to use a counter and increment it on every insertion. Alternatively, you could implement your own UUID-generating function, but I wouldn't go as far.
Example:
let object = {};
let createUniqueKey = ((counter) => () => counter++)(0);
let array = ["a", "b", "c"];
/* Create a unique key. */
let key = createUniqueKey();
/* Create a unique key to store the array. */
object[key] = array;
/* Use the key to get the array from the object. */
console.log(object[key]);
If instead, you want to use the array and based on that to create your key, the only solution that comes to my mind now is using a combination of toString and btoa (or simply the latter as it accepts array arguments). However, this method has some restrictions such as when the array contains objects and functions.
Example:
let object = {};
let createKey = (array) => btoa(array);
let array = ["a", "b", "c"];
/* Create a key to store the array. */
object[createKey(array)] = array;
/* Use the array to recreate the key and access the array inside the object. */
console.log(object[createKey(array)]);

Related

Javascript "Set" for Objects and Arrays

Does Javascript have a built-in type for making a set out of data-objects and arrays?
let set = new Set();
set.add({"language": "ecmascript"});
set.add({"language": "ecmascript"});
set.add({"language": "ecmascript"});
set.add({"language": "ecmascript"});
set.add([1,2,3]);
set.add([1,2,3]);
set.add([1,2,3]);
set.add([1,2,3]);
console.log(set);
The Set I'm using above is only useful for primitives.
The Set I'm using above is only useful for primitives.
That's incorrect, it works just fine for objects. The problem is that distinct objects with the same properties and property values are not equal, so doing set.add({"language": "ecmascript"}); twice adds two non-equal objects to the set (both with the same property name and value).
If you add the same object more than once, it won't be added a second time:
const set = new Set();
const obj = {"language": "ecmascript"};
set.add(obj);
set.add(obj);
console.log(set.size); // 1
Does Javascript have a built-in type for...
If you want objects with the same properties and values to be treated as equal, then no. You'd need to be able to specify a comparison operation, and there's no built-in Set in JavaScript that lets you define the comparison operation to use.
Obviously, you can create one. As a starting point, I'd probably use a Map keyed by the names of the properties on the object, sorted and turned into a string via JSON.stringify. (Although that won't work if you want to have Symbol keys as part of the definition of equality.) For instance, if you're only considering own properties:
const key = JSON.stringify(Object.getOwnPropertyNames(object).sort());
The value for an entry could be either just an array of the objects with those keys that you do a linear search on, or a second Map keyed by some kind of hash of the property values, depending on how many objects you need to handle...
In comments, I asked:
Do you only need to handle objects with JSON-serializable values?
and you answered:
I have a bunch of objects that are already serialized, but there are duplicates that I'd like to eliminate and then re-serialize.
Yeah, you can use a Set for that if you don't mind re-serializing, or a Map if you want to skip the re-serializing part:
const unique = new Map();
for (const source of serializedObjects) {
const sourceObject = JSON.parse(source); // Or parse from whatever serialization it is
// Build object adding properties in alpha order for stability
const keyObj = {};
for (const key of Object.keys(sourceObject).sort()) {
keyObj[key] = sourceObject[key];
}
// Save it using JSON.stringify, which uses ES2015 property order
map.set(JSON.stringify(keyObj), source);
}
const uniqueSourceStrings = [...map.values()];
Or for the de-serialized objects themselves:
const unique = new Map();
for (const source of serializedObjects) {
const sourceObject = JSON.parse(source); // Or parse from whatever serialization it is
// Build object adding properties in alpha order for stability
const keyObj = {};
for (const key of Object.keys(sourceObject).sort()) {
keyObj[key] = sourceObject[key];
}
// Save it using JSON.stringify, which uses ES2015 property order
map.set(JSON.stringify(keyObj), sourceObject); // <=================== changed
}
const uniqueSourceObject = [...map.values()];
// ^^================================================================== changed

angularjs : iterate array with key value pairs

I am creating an array like the following:
var arr =[];
arr['key1'] = 'value1';
arr['key2'] = 'value2';
If is use this array in ng-repeat tag, it is not displaying anything. Is there any way to make it work?
<div data-ng-repeat='(key,value) in arr'>{{key}} - {{value}}</div>
Is there any way to make it work?
The way to go, is to creat plain object (instead of array)
// instead of creatin of an Array
// $scope.myArr = [];
// we just create plain object
$scope.myArr = {};
...
// here we just add properties (key/value)
$scope.myArr['attempt1'] = {};
...
// which is in this case same as this syntax
$scope.myArr.attempt1 = {};
Thee is updated plunker
Check more details what is behind for example here:
Javascript: Understanding Objects vs Arrays and When to Use Them. [Part 1]
Your associative array is nothing but an object, as far as JavaScript is concerned. IMO Associative arrays and Objects are almost same.
Ex: Your arr['key1'] = 'value1'; can be called as console.log(arr.key1);
To make your code work, you need to change the array declaration by removing [] and replacing with {} (Curly braces)
Like this var arr = {};

How to store number of object element of array in another array?

im trying to store some object element from one array to another so lets say i have this array of objects
var Array = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
and i want to store the first two object in this array to another array so it would like be
var SubArray =[{name:'Fadi'},{name:'Joseph'}];
thanks in advance for any help.
You can use slice method for this:
var SubArray = Array.slice(0,2);
Please note that Array is reserved JS global object. You need to use different name for that variable. So your code should be for example:
var MyArray = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
var SubArray = MyArray.slice(0,2);
If you need conditional logic you want Array.filter(). If you know you always want the items by index then use slice as in antyrat's answer.
var originalArray = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
var subArray = originalArray.filter(function(obj,index) {
return obj.name=="Fadi" || obj.name=="Joseph";
})

Every character in an array being recognized with ".hasOwnProperty(i)" in javascript as true with Google Apps Script

This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.

javascript using numeric array as associate array

In Javascript, I have an array of objects, users, such that users[1].name would give me the name of that user.
I want to use the ID of that user as the index instead of the ever increasing counter.
For example, I can initiate the first user as users[45].
However, I found that once I do users[45], javascript would turn it into a numeric array, such that when I do users.length, I get 46.
Is there anyway to force it to treat the number as string in this case. (" " doesn't work)?
You cannot use arrays for this sort of function in JavaScript — for more information, see "Javascript Does Not Support Associative Arrays."
Make sure you initialize the users variable as an Object instead. In this object you can store the arbitrary, non-sequential keys.
var users = new Object();
// or, more conveniently:
var users = {};
users[45] = { name: 'John Doe' };
To get the number of users in the object, here's a function stolen from this SO answer:
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var users = {};
// add users..
alert(Object.size(users));
Hans has the right answer here. Use keys on an object, not an array. I'd suggest you read these two references:
http://www.quirksmode.org/js/associative.html and
http://blog.xkoder.com/2008/07/10/javascript-associative-arrays-demystified/
Trying to make an associative array out of an array object is non-standard and can cause problems (for example .length will be zero). Use keys on an object instead.

Categories

Resources