getting and displaying a javascript object by index - javascript

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.

Related

Make the hash value unique in 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.

Search array for string - returning -1

I've been reading lots of StackOverflow answers which tell me that, in Javascript, the best way to search an array for a particular string is use indexOf(). I have been trying to make this work for a while now, and I need some help with it.
I am making a shop in a text-adventure game. These are the values I am using:
The array shopCosts:
shopCosts = [20, 25];
The array shopItems:
shopItems = [["Sword", "Shield"]];
I dynamically create radiobuttons by looping through shopItems:
for(var i = 0; i < array.length; i++)
{
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i] + " - " + shopCosts[i] + " Gold"));
// Add it to the list:
list.appendChild(item);
var label = document.createElement("label");
var radio = document.createElement("input");
var text = document.createTextNode(array[i]);
radio.type = "radio";
radio.name = "shop";
radio.value = array[i];
radio.onclick = function () { addValue(this.getAttribute("value"), shopCosts, shopItems) }
label.appendChild(radio);
label.appendChild(text);
document.body.appendChild(label);
}
This is the part in question:
radio.onclick = function () { addValue(this.getAttribute("value"), shopCosts, shopItems) }
My logic was basically to assign values to each dynamically created radiobutton, and if one was pressed, get the value (so, the name of the item you wanted to buy) and then search shopItems for that particular string for the index value. Once I had that, I would look in the same "parallel" list shopCosts to find the price.
I used console.log() to see what variables were in play. When I clicked on the radio button, this function is called:
function addValue(nameOfItem, shopCosts, shopItems)
{
var positionOfShopItem = shopItems.indexOf(nameOfItem);
console.log(positionOfShopItem);
console..log(nameOfItem);
console.log(shopItems);
}
Surely, the console.log() would return the position of the named item? To prove to myself I'm not going crazy, here's what the Dev Tools say:
-1
Sword
[Array[2]]
0: "Sword"
1: "Shield"
Sword is clearly in the array, in position 0, so why is indexOf() returning -1?
Any help appreciated!
As I alluded to in my comment, its because shopItems does not contain an array of strings, it contains a single element, where that one element is an array of strings. I suspect your code would work just fine if you removed the extra square braces
var shopItems = ["Sword", "Shield"];
I realize you've already fixed the bug, but I urge you to consider a different approach to the problem. These two principles will not only solve the problem in a cleaner way, but they also give you a new way to think about similar problems in the future:
Never use parallel arrays. Use a single array of objects instead.
In your main loop that appends the items, put the main body of the loop in a function.
If you follow these two ideas you gain several benefits. The code becomes much more straightforward, easier to maintain, and you don't have to do any array lookups at all!
Each shop item is packaged up as a single object in the array, like this:
var shopItems = [
{ name: 'Sword', cost: 20 },
{ name: 'Shield', cost: 25 }
];
So if you have a reference to the shop item as a whole, say in a variable called shopItem, then you automatically have all of its properties available: shopItem.name and shopItem.cost. This lets you also easily add more bits of data to a shop item, e.g.
var shopItems = [
{ name: 'Sword', cost: 20, dangerous: true },
{ name: 'Shield', cost: 25, dangerous: false }
];
and now shopItem.dangerous will give you the appropriate value. All without any array lookups.
Making the main loop body into a function adds a further benefit: Inside that function, its parameters and local variables are preserved each time you call the function (this is called a closure). So now you don't even have to fetch the list item value and look it up - you already have the appropriate shopItem available in the code.
Putting this together, the code might look like this:
var shopItems = [
{ name: 'Sword', cost: 20, dangerous: true },
{ name: 'Shield', cost: 25, dangerous: false }
];
var list = document.getElementById( 'list' );
for( var i = 0; i < shopItems.length; ++i ) {
appendShopItem( shopItems[i] );
}
// Alternatively, you could use .forEach() instead of the for loop.
// This will work in all browsers except very old versions of IE:
// shopItems.forEach( appendShopItem );
function appendShopItem( shopItem ) {
// Create the list item:
var item = document.createElement( 'li' );
// Set its contents:
item.appendChild( document.createTextNode(
shopItem.name + ' - ' + shopItem.cost + ' Gold'
) );
// Add it to the list:
list.appendChild( item );
var label = document.createElement( 'label' );
var radio = document.createElement( 'input' );
var text = document.createTextNode( shopItem.name );
radio.type = 'radio';
radio.name = 'shop';
radio.value = shopItem.name;
radio.onclick = function () {
addValue( shopItem );
};
label.appendChild( radio );
label.appendChild( text );
document.body.appendChild( label );
}
function addValue( shopItem ) {
console.log( shopItem );
alert(
shopItem.name +
' costs ' + shopItem.cost + ' and is ' +
( shopItem.dangerous ? 'dangerous' : 'not dangerous' )
);
}
New fiddle (with a tip of the hat to Jamiec for the original fiddle)
As you can see, this makes the code much easier to understand. If you have a shopItem, you automatically have its name, cost, and any other property you want to add. And most importantly, you never have to keep track of putting your values in the same order in two, three, or even more different arrays.
shopItems is an Array of Arrays. The 0 index of shopItems contains another array which contains:
["Sword", "Shield"]
So when you are trying to find the "Sword" item or "Shield" Item inside of shopItems it is returning -1 because it cannot find either inside of the array.
Change
shopItems = [["Sword", "Shield"]];
To
shopItems = ["Sword", "Shield"];
And that will fix your issue.
I've fixed it!
Removing the double square brackets resulted in this mess. So, as a workaround, I simply added [0] to var positionOfShopItem = shopItems.indexOf(nameOfItem); to get var positionOfShopItem = shopItems[0].indexOf(nameOfItem);
Thanks for everyone's help.

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.

How to iterate an array of objects and print out one of its properties

I have the following code in a display template in sharepoint, I have an array of objects and I need to have the following result.
Name1
Name2
Name3
So I can replace the default rendering of sharepoint multiple people user field with a tooltip.
However, I dont know how to iterate and then concatenate:
Screenshot:
Code:
// List View - Substring Long String Sample
// Muawiyah Shannak , #MuShannak
(function () {
// Create object that have the context information about the field that we want to change it's output render
var projectTeamContext = {};
projectTeamContext.Templates = {};
projectTeamContext.Templates.Fields = {
// Apply the new rendering for Body field on list view
"Project_x0020_Team": { "View": ProjectTeamTemplate }
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(projectTeamContext);
})();
// This function provides the rendering logic
function ProjectTeamTemplate(ctx) {
var projectTeamValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
//newBodyvalue should have the list of all display names and it will be rendered as a tooltip automaticlaly
return "<span title='" + projectTeamValue + "'>" + newBodyValue + "</span>";
}
You can "map" property values from the projectTeamValue array objects into a new array, then "join" those values together (using ", " as the separator in this example) all in one go:
var newBodyValue = projectTeamValue.map(function(person) {
return person.value;
}).join(", ");
If your projectTeamValue array looked like:
[{ value: "Name1" }, { value: "Name2" }, { value: "Name3" }]
Then newBodyValue would be:
"Name1, Name2, Name3"
jsFiddle Demo
Side note: Array.prototype.map() was not available in IE 8 and below but should work in every other browser.

make json from table

I want to make specific json from table. I have a table, which has rows and 4 columns.
Here is my table I want to build an jsonarray from the table.
First value in the left column is key of json and last value in the right column is a valueof json.
I mean I want to get from table jsonarray, it must look as
json_from_form = [{color: 'id',
name: "mouse",
x: "table",
y: "book"}];
I have tried to build json, but have a problem with structure and setting a key in json object.
Please help me to buld right structure of json object.
var json_from_form_tmp = {};
$('#table').find('tbody tr').each(function (i) {
//var name = $(this).find('td:first').text();
json_from_form_tmp[i] = {
imd: $(this).find('td:eq(3) input').val()
};
});
console.log(json_from_form_tmp);
Here is my DEMO
You should use the jQuery map-function for this, here is an example:
$(function () {
var m = $("table tr").map(function (index, e) {
return {
color: $(e).children().eq(0).text(),
name: $(e).children().eq(1).text()
}
}).get();
});
Where m will be an array of objects as defined inside the map function.
To set a property of the object (json_from_form_tmp), use the ['propertyName'] notation.
//get the name of the property from the first column
var name = $(this).find('td:first').text();
//use that name as the name of the property. Your value fetch was right!
json_from_form_tmp[name] = $(this).find('td:eq(3) input').val();
Here is your fiddle with a tiny modification.
http://jsfiddle.net/bMzq8/32/

Categories

Resources