Make the hash value unique in javascript? - javascript

For example I am having the hash
var sample={};
sample["test"] = [];
sample["test"].push({name: "test"});
sample["test"].push({name: "test"});
The sample hash should only contain unique values.

Yes i got the solution for that
var sample = [{ id : 1, name : 'Name' }, { id : 1, name : 'Name' }];
var obj = { id : 1, name : 'Name' };
var sample = [obj, obj];
uniq(sample)

Hej man it isn’t possible to got another hash value from 2 same value’s.
For simplify a hash operation is likely like plus so you got 1 + 2 = 3.
It is not that easy but I hope you got he point.

Related

jQuery object array from input

I have a few inputs with data attribute and value. I want to get data attribute for key and for value to get value from input. And where the value repeats it to be recorded only once.
Here is my demo https://jsfiddle.net/7L3eugqp/.
The result that I want should be look like that:
"A_1_1": {1, 2, 3},
"A_1_2": {4, 5, 6}
I will be grateful if someone give me advice how to do this. Thanks.
You were overriding the first dataset each time your loop found another element.
var datasets = {};
$('.project').each(function(index, value) {
catName = $(this).data("prefix");
datasets[catName] = datasets[catName] || {
label : catName,
data: []
};
datasets[catName].data.push($(this).val());
});
console.log(datasets);
If you don't want to have 1 twice (treat them as distinct sets), you can enclose the push call in this if statement:
if (datasets[catName].data.indexOf($(this).val()) === -1) {
you need to use 2 loop. the first to create datasets and the second to push data :
$('.project').each(function(index, value) {
catName = $(this).data("prefix");
if(!$.contains(datasets,catName)){
datasets[catName] = {
label : catName,
data: []
};
}
});
$('.project').each(function(index, value) {
catName = $(this).data("prefix");
datasets[catName].data.push($(this).val());
});
console.log(datasets);
https://jsfiddle.net/y6c5gw7o/

getting the key/pair values out of an object that in an object

Objects thats returned:
ref.orderByChild('name').once('value').then(function(snapshot){
var results = snapshot.val();
When i log results the image is what i get, Ive been trying to access the value of 'active' for each of the three objects, phishing, information and techniques.
This is my first JS application sorry if its an easy one but couldn't find an answer else where that worked.
There are two (common) ways to do this: the Firebase way and the regular JavaScript way.
the Firebase way
Since it seems you're returning a list of nodes, I'll start with the Firebase way.
ref.orderByChild('name').once('value').then(function(snapshot){
var actives = {};
snapshot.forEach(function(childSnapshot) {
var result = childSnapshot.val();
var key = result.key;
var active = result.active;
actives[key] = active;
}
console.log(actives);
}
So we're using Firebase's Snapshot.forEach() method here to loop over the child nodes.
the regular JavaScript way
Alternatively you can get the value of the entire snapshot as you already do and use plain old JavaScript to get the result you need. Jatin's answer shows one way to do that, but here's another:
ref.orderByChild('name').once('value').then(function(snapshot){
var results = snapshot.val();
var keys = Object.keys(results); // ["information", "phishing", "techniques"]
var actives = {};
keys.forEach(function(key) {
actives[key] = results[key].active;
});
console.log(actives);
}
So in this case we're using Object.keys() to get the child node names and then loop over that array with JavaScript's Array.forEach().
var snapshot = {
"information" : {
"active" : "y",
"name" : "information"
},
"phishing" : {
"active" : "z",
"name" : "phishing"
},
"techniques" : {
"active" : "x",
"name" : "techniques"
},
};
console.log(snapshot.information.active);
console.log(snapshot.phishing.active);
console.log(snapshot.techniques.active);

The JSON parsed into HTML, how objects are mapped to corresponding HTML?

For example, the following JSON:
{
"A" : [{
name : "admin",
email:"xxx#msn.com"
},{
name : "anly",
email:"xxx#msn.com"
}]
"B" : [{
name : "beta",
email:"xxx#msn.com"
},{
name : "b",
email:"xxx#msn.com"
}]
}
Html formatted as follows:
<ul>
<li>admin</li>
<li>anly</li>
<li>besta</li>
<li>bestb</li>
</ul>
How By clicking li, found to their corresponding object?
I think the method is:
1, by traversing JSON find, but this way is time-consuming, not simple
2, which is bound to the data key and index attributes above and through the key index to find, but if some of the more complex data structures, as too cumbersome, and do not know that there is no other better way to achieve it?
The above content is translated through Google, I do not know whether a clear description of my problem?
Here are two examples of what I wrote myself realized:
http://jsfiddle.net/18q41mfr/
It all depends on your requirements. How large will this JSON object be and how frequently will it change?
For small or constantly changing JSON objects, it might be just fine to do the method 1.
For large and constant JSON objects, go with method 2. A cleaner way to achieve method 2 that you've suggested is to make use of the Underscore.js values and groupBy method.
Merge all values in your object with the var merged = _.values(object)
Group by name var formatted = _.groupBy(merged, 'name');
Resulting JSON is such:
{
admin: {
name : "admin",
email:"xxx#msn.com"
},
anly: {
name : "anly",
email:"xxx#msn.com"
},
...
}
Use the following code to get the value in your onclick event function on your li element:
formatted[this.innerHTML].email
It seems that you're already using jQuery; you can simply stuff the object references into your HTML elements using .data().
Internally, an object reference map is maintained and the HTML element stores the reference key in a special property name.
var items = {
"type_a" : [{
name : "test",
color : "red"
},{
name : "test",
color : "blue"
}],
"type_b" : [{
name : "test",
color : "orange"
},{
name : "test",
color : "yellow"
}]
};
for (var i in items) {
for (var j = 0; j < items[i].length; j++) {
$('<li>', {text: items[i][j].name})
.data(items[i][j])
.appendTo('#items');
}
}
$("#items").on("click", "li", function() {
var obj = $(this).data();
$("#detaila").html('name:' + obj.name + '<br>color:' + obj.color + '<br>' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id="items"></ul>
<div id="detaila"></div>
<div id="detailb"></div>
Your second method is kind of good enough.
Maintain a global object myObjs for searching, whose keys are name and the values are object itself.
For each of the objects like:
var obj = {
name : "beta",
email:"xxx#msn.com"
}
myObjs[obj[name]] = obj; // If the name is not unique, add an id.
Then bind the key to the HTML element:
<li data-key="admin">admin</li>
When the element is clicked, find the key, query myObjs and find the obj. Something like (assume you are using jQuery):
$('ul').on('click', 'li', function() {
var $this = $(this);
var name = $this.data('key');
var obj = myObjs[name];
console.log(obj); // Here is your corresponding object.
});
Cons: extra memory
Pros: fast.

getting and displaying a javascript object by index

var pdata = [{ Name: "Apples", Price: 1.99 },{ Name: "Bananas", Price: 2.45 }];
$('#add1').click(function () {
var selected = $('#produceList option:selected').index();
I have a variable set to an index and I want to get and display the javascript object by the var selected index
HTML
<div class-'item'></div>
JS
$('#add1').click(function () {
var selected = $('#produceList option:selected').index(),
item = pdata[selected];
$('.item').html(item.Name + ', ' + item.Price);
});
JSFIDDLE
If you have the index, you would just do
pdata[index];
so in your example
$('#add1').click(function () {
var index = $('#produceList option:selected').index();
var selected = pdata[index];
})
assuming the code you give in the question gives the index of the selected item.
The pairings are referenced using a simple array index, so your values are:
pdata[0] ---> {Name="Apples", Price=1.99}
pdata[1] ---> {Name="Bananas", Price=2.45}
To get to the specific attributes of the object, you need to use the name of the attribute, so your values are:
pdata[0].Name ---> "Apples"
pdata[0].Price ---> 1.99
pdata[1].Name ---> "Bananas"
pdata[1].Price ---> 2.45
So, to access the information that you want, you would use pdata[index].Name and pdata[index].Price, once you have retrieved the index.

Dynamically adding members to a javascript object

I'm working on a scoring script for contract bridge, just for giggles. I'm storing the game as an object:
var game = {
team1 : { player1 : prompt("Team 1, first player: "), player2 : prompt("Team 1, second player:") },
team2 : { player1 : prompt("Team 2, first player: "), player2 : prompt("Team 2, second player:") },
}
function deal(bid){
console.log("The bid was " + bid);
game.hand = {"bid" : bid , "made" : undefined};
score();
}
So what I'd like to do though, better than this, is to keep a history of the games played this session. I'd like to, in pseudocode, do something like this:
game.(hand + (hand.length+1))
or something kind of like that; basically auto-increment a certain object within an object. I'm not so sure an array would would here, but perhaps? I'm open to suggestions/bettering of my code.
PS - I'd prefer to do this in javascript, not jQuery, Prototype, Dojo, MooTools... or any other library. Thanks!
EDIT
Sorry, let me clarify: The result after playing 3 hands or so would be an object like this:
var game = {
team1 : { player1 : prompt("Team 1, first player: "), player2 : prompt("Team 1, second player:") },
team2 : { player1 : prompt("Team 2, first player: "), player2 : prompt("Team 2, second player:") },
hand1 : { bid : 2 , made : 2 } ,
hand2 : { bid : 1 , made : 4 } ,
hand3 : { bid : 3 , made : 1 } ,
hand4 : { bid : 2 , //and made hasn't been set yet because we're mid-hand
}
Given your pseudocode, you can do the following:
game[hand + (hand.length+1)]
i.e. game["prop"] == game.prop - both provide access to the same property.
Old question, I see but I have a need to do something similar. I'd vote up the answer but I'm not allowed.
It appears the fastest way to do this is to access the object like a hash / associative array.
var d = {};
var z = "hand";
d[z+1] = "foo";
console.log(d.hand1);
Test this out in firebug. Seems to work pretty well.
JS does not seem to have an php equivalent to force resolution of the variables as in the curley braces around an expression.
d->{z+1} = "foo"; // can't find anything like this in JS.
Hope that helps,

Categories

Resources