arranging elements in to a hash array - javascript

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.

Related

Data pass as objects as well as an array?

I'm developing a system for manage directors in group of companies. I need to filter directors for companies as assigned. After I pass data from controller to view, when selecting companies the filter shows incorrect results.
The above results will show when I console.log(this.directorships) those. I think it's because for single data it'll show as an array. But if those multiple it'll show as objects.
I'm looping those inside for loop as follows to print results.
for (let i = 0; i < this.directorships.length; i++) {
single_director = this.directorships[i].director_profile;
finalArray.push(single_director);
}
MyController.php
public function activeBoard($company_id){
$directorship = Directorship::with(['director_profile'])
->where('master_data_id',$company_id)
->get();
$active_directors = $directorship->where('active',1);
return $active_directors;
}
Can anyone please tell me what's the mistake I have done here? Or are there any methods to do what I expect?
It's hard to tell from the screenshots, but Objects in JavaScript are not iterable using a standard for loop, and don't have a length property by default. You should first check whether the directorships is an array, and then iterate or read suitably. For example:
let directorships_is_array = Array.isArray(directorships);
if(directorships_is_array) {
// ... loop through array
}
else {
// ... perform other function on object
}
There are a number of ways to iterate through an object, and get an objects length. The new for in loops can iterate through an object. For example:
for(let director in directorships) {
console.log(director);
}
You can also get the length of the Object using something like, let directors_length = Object.keys(directorships).length and then do something like this:
let number_of_directorships = Object.keys(directorships).length;
for(let i=0; i<number_of_directorships; i++) {
// ... iterate here
}
you need to use query like this you have initialize query before the condition
public function activeBoard($company_id){
$directorship = Directorship::where('master_data_id',$company_id)->where('active',1)->with('director_profile')->get();
return $directorship;
}

How can I dynamically index through datalayer tags in GTM?

I'm using the DuracellTomi datalayer plugin to push cart data from woocommerce to a GTM model to handle some tracking.
The DuracellTomi plugin pushes content to the transactionProducts[] array in the following format:
transactionProducts: Array[1]
0 : Object
category:""
currency:"USD"
id:8
name:"Test"
price:100
quantity:"1"
sku:8
I'd like to loop through this array and unstack it into three separate arrays, pricelist, skulist, and quantitylist. Currently I anticipate doing so as some variation on
//Get Product Information
if(stack = {{transactionProducts}}){
for(i = 0; i < stack.length; i++) {
if(stack.i.sku){
skulisttemp.i = stack.i.sku;
}
if(stack.i.price){
pricelisttemp.i = stack.i.price;
}
if(stack.i.sku){
quantitylisttemp.i = stack.i.quantity;
}
}
{{skulist}} = skulisttemp;
{{pricelist}} = pricelisttemp;
{{quantitylist}} = quantitylisttemp;
}
Obviously this is not going to work because of how the tag referencing is set up, but I'm wondering if anyone has dealt with this and knows what the best way to index through these arrays might be. (For those who don't know, the square bracket array call doesn't work with GTM variables and instead the . format is used instead.)
You would need to create 3 variable type custom javascript function that picks your required value from dataLayer and returns it in an array.
Something like
function(){
var products = {{transactionProducts}};
var skuArray = [];
for(i = 0; i < products.length; i++) {
if(products[i].sku){
skuArray.push(products[i].sku)
}
}
return skuArray
}
hope this helped you :)

How to create multiple objects based on dynamic data?

Basically what i'm doing, is trying to create my own steam market JSON, by HTML parsing.
Example of how I'm currently doing that :
var url = 'http://steamcommunity.com/market/search?appid=730'
var itemDiv = $("<div></div>")
$.get(url).success(function(r){
data = $(r).find('stuff i need')
itemDiv.append(data)
})
and now say I wanted to find names of the items in the div, i would do something like :
itemDiv.find('x').each(function(){
var name = $(this).find("y").text()
// console.log(name) [or do whatever is needed ect]
})
As I mentioned before, I need to return objects based on that data in the format of:
var item = {name:"",price:0}
However, things like price will always be changing.
Based on the data thats in the div, the final product would look along the lines of :
var x = {name:"a",price:1}
var x2 = {name:"a2",price:2}
How do I go about doing this? I thought maybe i could store the data in an array, and then do something like
for(x in y){
return object
}
or something along those lines.
Sorry if this seems like a bonehead question, I'm pretty new to javascript.
clarification: i'm trying to figure out how to return multiple objects based on the data inside the div.
Here is the code that builds an array of objects based on two arrays (assuming they are of equal length).
function buildStocks() {
// Names and prices can also be passed as function arguments
var names = ['a', 'b', 'c'];
var prices = [1, 2, 3];
var result = []; // Array of these objects
for (var i = 0; i < names.length; i++) {
result.push({
name: names[i],
price: prices[i]
});
}
return result;
}

How to retrieve an object from a long list having a given (key,value) pair?

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;
});

access javascript array element by JSON object key

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

Categories

Resources