Say I have this JSON object:
var images = {"success":"true", "images":[
{"id":"1234","url":"asdf","tags":["cookie","chocolate"]},
{"id":"5678","url":"qwer","tags":["pie","pumpkin"]}
]};
What would be the most efficient way to get the url of the image with an id of 5678? Can use jQuery.
Because it's an array and you're looking for an embedded property, not just a simple array value, there isn't really a super-efficient way to find it. There's the brute force mechanism of just walking through the array and compare each id to what you're looking for.
If you're going to be looking up these kinds of things in this same data structure multiple times and you want to speed it up, then you can convert the existing data structure into a different data structure that's more efficient for accessing by ID like this:
var imagesById = {
"1234": {"url":"asdf","tags":["cookie","chocolate"]},
"5678": {"url":"qwer","tags":["pie","pumpkin"]}
}
Then, finding an object by id is as simple as this:
imagesById["1234"]
url = $.grep(images.images, function(item) { return item.id === '5678' })[0].url;
Unless the IDs are sorted, you can't do better than plain old iteration:
var images = {"success":"true", "images":[
{"id":"1234","url":"asdf","tags":["cookie","chocolate"]},
{"id":"5678","url":"qwer","tags":["pie","pumpkin"]}
]};
var inner = images.images,
targetId = '5678',
found = null;
for (var i=0; i<inner.length; i++) {
if (inner[i][id] === targetId) {
found = inner[i];
// do stuff...
break;
}
}
You'd have to loop through the array:
$.each(images.images,function(i,img) {
if(img.url == "5678") {
//do whatever you want with this url
}
}
Related
I have this stored in the session:
What I'm looking to do is assign each object in the JSON as a variable so I can add them to the DOM appropriately.
This works but prints everything out:
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
$(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div');
}
What I'd like is something like this, but it doesn't work:
var div1 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.cart-contents')));
var div2 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.footer-cart-contents')));
var div3 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'div.widget_shopping_cart_content')));
Any help would be greatly appreciated. Thank you!
Getting the same value from the storage several times is not a good idea. In addition, you need better names for your variables.
var json = sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
if (json) {
var data = JSON.parse(json);
if (data) {
var cart_link = $(data['a.cart-contents']),
footer_link = $(data['a.footer-cart-contents']),
widget_div = $(data['div.widget_shopping_cart_content']);
}
}
So it appears you have set selectors as keys of the object so you could iterate those keys to get each selector.
The propose of those selector keys is not 100% clear. I am assuming that those selectors are the elements you want to insert the html strings into and that $() means you are using jQuery
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
var data = JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
$.each(data, function(selector, htmlString){
$(selector).append(htmlString)
});
}
I have stored certain information in localStorage like-
$localStorage.recent = [{'id':1,'name':'abc','is_availbale':1},{'id':2,'name':'xyz','is_availbale':1},{'id':3,'name':'pqrs','is_availbale':0}];
having another array which is only having id's of certain people like(array_second can have only those id's which are already there in
$localStorage.recent)-
array_second=['3'];
I want to delete those entries from $localStorage.recent which are corresponding to the id's in array_second. Expected output to be-
$localStorage.recent = [{'id':1,'name':'abc','is_availbale':1},{'id':2,'name':'xyz','is_availbale':1}];
You're just handling a standard array. The ngstorage library doesn't give you any additional functionality here.
For example:
$localStorage.recent = $localStorage.recent.filter((person) => {
return second_array.indexOf(person.id) !== -1;
});
This code may useful to you, written in javascript
var fullArr =[{'id':1,'name':'abc','is_availbale':1{'id':2,'name':'xyz','is_availbale':1},{'id':3,'name':'pqrs','is_availbale':0}];
var toDelArr = [1];
for(var i=0;i<fullArr.length;i++){
if(toDelArr[0] == fullArr[i].id){
fullArr.splice(i, 1);
}
}
Hi have a long list of objects like that:
var myLongList = [
{id="1", desc:"ahahah"},
{id="2", desc:"ihihih"},
{id="3", desc:"ohohoh"},
...
{id="N", desc:"olala"}
]
I need to retrieve the object with id="14575". Since my list is quite long and I have to make a lot of such retrievals, I would prefer not to loop through the list to get my object.
So far, I use a function to index my array from a column:
function index(js, indexColumn){
var out={};
var o;
for (var key in js) {
o = js[key];
out[o[indexColumn]]=o;
}
return out;
}
A call to var myLongListIndexed = index(myLongList, "id"); builds an indexed list and myLongListIndexed["14575"] returns my beloved object.
Is there a more standard way to retrieve objects from lists based on a (key,value) pair?
Sounds like pretty much the most sensible way to do it, except that it's not a good idea to use for..in with arrays. Better to use a regular for loop or js.forEach(...).
Like this:
for (var i = 0; i < js.length; i += 1) {
o = js[i];
out[o[indexColumn]]=o;
}
or this (requires ES5):
js.forEach(function(el) {
out[el[indexColumn]] = el;
});
jQuery version (doesn't require ES5):
$.each(js, function() {
out[this[indexColumn]] = this;
});
I have an array that looks like this
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]
I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)
Zips[rows[i].Zipcode].Count
I know that's not right and am hoping that there is a solution without looping through the result set every time?
Thanks
I know that's not right and am hoping that there is a solution without
looping through the result set every time?
No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:
var filteredZips = Zips.filter(function(element) {
return element.Zip == 92880;
});
if (filteredZips.length > 0) {
// we have found a corresponding element
var count = filteredZips[0].count;
}
If you had designed your object in a different manner:
var zips = {"92880": 1, "91710": 3, "92672": 0 };
then you could have directly accessed the Count:
var count = zips["92880"];
In the current form, you can not access an element by its ZIP-code without a loop.
You could transform your array to an object of this form:
var Zips = { 92880: 1, 91710: 3 }; // etc.
Then you can access it by
Zips[rows[i].Zipcode]
To transform from array to object you could use this
var ZipsObj = {};
for( var i=Zips.length; i--; ) {
ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}
Couple of mistakes in your code.
Your array is collection of objects
You can access objects with their property name and not property value i.e Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip.
If you want to find the value you have to loop
If you want to keep the format of the array Zips and its elements
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
MappedZips[Zips[i].Zip] = Zips[i];
}
MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}
// then you can get Count by O(1)
alert(MappedZips[92880].Count);
// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);
jsFiddle example
function getZip(zips, zipNumber) {
var answer = null;
zips.forEach(function(zip){
if (zip.Zip === zipNumber) answer = zip;
});
return answer;
}
This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.
did you try this?
Zips[i].Zip.Count
I am trying to break a javascript object in to small array so that I can easily access the innerlevel data whenever I needed.
I have used recursive function to access all nodes inside json, using the program
http://jsfiddle.net/SvMUN/1/
What I am trying to do here is that I want to store these in to a separate array so that I cn access it like
newArray.Microsoft= MSFT, Microsoft;
newArray.Intel Corp=(INTC, Fortune 500);
newArray.Japan=Japan
newArray.Bernanke=Bernanke;
Depth of each array are different, so the ones with single level can use the same name like I ve shown in the example Bernanke. Is it possible to do it this way?
No, you reduce the Facets to a string named html - but you want an object.
function generateList(facets) {
var map = {};
(function recurse(arr) {
var join = [];
for (var i=0; i<arr.length; i++) {
var current = arr[i].term; // every object must have one!
current = current.replace(/ /g, "_");
join.push(current); // only on lowest level?
if (current in arr[i])
map[current] = recurse(arr[i][current]);
}
return join;
})(facets)
return map;
}
Demo on jsfiddle.net
To get the one-level-data, you could just add this else-statement after the if:
else
map[current] = [ current ]; // create Array manually
Altough I don't think the result (demo) makes much sense then.