Creating Nested Objects on the Fly With Javascript - javascript

I'm new to Javascript coming from a Python background, where it's easy to created nested data using custom dictionaries and .get methods. What I'm trying to do is created a nested object of artist data that takes on this form: artistDict[artist][albumName] = albumYear. I need to create this object on the fly by iterating over an iterable of album objects. Here's the code I'm currently using:
albumDict = {};
albums.forEach(function(item){
albumDict[item.artist][item.name] = item.year;
});
document.write(albumDict);
This doesn't work, which isn't surprising, since something like this wouldn't work in Python either. However, in Python I could use a .get method to check if an entry was in the dictionary and create it if not -- is there something similar, or any other utility that I could use to achieve my goal in JS?

This should work: (if the property doesn't exist you should initialize it..)
albumDict = {};
albums.forEach(function(item){
albumDict[item.artist] = albumDict[item.artist] || {};
albumDict[item.artist][item.name] = item.year;
});

Try this:
albums.forEach(function(item){
albumDict[item.artist] = albumDict[item.artist] || {};
albumDict[item.artist][item.name] = item.year;
});
The first line in that function sets albumDict[item.artist] to a new object if it doesn't exist, yet. Otherwise, it sets it to itself.
Then, you can just set the year on the dict entry.

Related

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 = {};

javascript how to add new object into object after it has been created

This is my object:
var example = {"119":{"bannerId":"119","overlay":"3","type":"1",...},"210":{"bannerId":"210","overlay":"3","type":"1",...},...}
In this way I can very easily access or modify object. For example if I want to add new property I simply call this:
example[119].newProperty = 1;
And very easily access it:
alert(example[119].newProperty)
alert(example[210].type)
By knowing banner id, I can access any data from any scope of code, this is the reason I chose this pattern. The problem is that I need to add new object inside example after it has been created. For example I need to push this into example:
{"30":{"bannerId":"119","overlay":"3","type":"1",...}}
And I don't know if this is possible. Is it? One way to solve this problem would be to use array, so example would be array and each key would carry object, and I could push into array new key with object. But I am not sure if this is proper way because key will start with 200, 300, ... console.log(example) shows undefined for all keys before 200. Is fine to have so many empty keys? Is any other better way?
EDIT:
I realized this can be done also with object. The problem was because I was trying to assign new property directly into new object like this:
example[200].example3 = 2;
guessing it is enough that example object is created. What I was missing is this line:
example[200] = {}
Thanks for answers, it works now!
var example = {};
example["30"] = {"bannerId":"119","overlay":"3","type":"1"}
console.log(example);
If its inside a loop you can also try something like below.
var i = 0;
var example = {};
for (i=0; i<10; i++) {
example[i] = {bannerId : i+1 , someOtherItem : i + "Hello"}
}
console.log(example);
example[30] = {"bannerId":"119","overlay":"3","type":"1",...};
You can always access (and assign) ad hoc keys of objects, even if you didn't define them in the first place.
So for your example you can just do:
example["30"] = {... /*your new object*/...}
It seems that you want to extend your object, you could use jQuery or underscore more or less like this:
$.extend(true, example, { "30": { objectId: "201" }}); // deep copy
If you don't want to use any library simply do:
example["30"] = myObj["30"];

Reading an object's value in JavaScript

I want to get the features from my layer. So I'm requesting WMSGetFeatureInfo method after a successful request for GetFeatureInfo on my layer.
The returned object is structured like this:
I can read values like BEVDICHTE with var bevdichte = features.BEVDICHTE and so on.
But when I want to get the value of the_geom with var the_geom = features.the_geom it returns an object. Yes it is nested so this is intended but my question is how to get the value ol.geom.MultiPoint
from the_geom?
EDIT:
Unfortunately var target = features.the_geom['actualEventTarget_']; will just return another 'actualEventTarget_' object. This is because the the_geom object is nested into infinity. I attached another screenshot to describe my problem. There are many more nested eventTargets following. Yet I was not able to get the property ol.geom.MultiPolygon.
To access a nested array, just use brackets: '[ ]'
var nestedArray = [[1,2], [3,4]];
var nestedArrayValue = nestedArray[0][0];
// --> returns 1
With your example:
var target = features.the_geom['actualEventTarget_']
By the way, from the looks of it var the_geom = features.the_geom doesn't seem like an array. It has keys, mapped to a value, are you sure this is an array, not an object?

How can I copy the contents of a Javascript object to an empty one?

I have a Javascript object (JSON returned from a database) for use in an Angular site:
[{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','widget_discount':'20'},{'widget_id':'2','widget_name':'Red Widget','widget_description':'A fantastic red widget','widget_discount':'0'}]
I want to process this information before I use it in my view - say I want to alter the discount or perform some other operations. Therefore I want to make a new object, iterate through my JSON, and write certain values from the JSON object to the new, blank object.
For now I've just been trying to test copying one value from the old array to a new one, in my Angular controller:
WidgetSvc.fetchWidgets().success(function(response){
var rawWidgets = response
var widgetsOutput = {}
for (var i in rawWidgets){
widgetsOutput[i].widget_id = rawWidgets[i].widget_id
}
But this throws a cannot set property 'widget_id' of undefined error. I suspect I'm not initializing the new object properly.
What am I doing wrong?
You just forgot to set you nested object before setting property :
var rawWidgets = [{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','widget_discount':'20'},{'widget_id':'2','widget_name':'Red Widget','widget_description':'A fantastic red widget','widget_discount':'0'}];
var widgetsOutput = {}
for (var i in rawWidgets){
widgetsOutput[i] = {}
widgetsOutput[i].widget_id = rawWidgets[i].widget_id
}
console.log(widgetsOutput)
JSON != Javascript Object. You can JSON.parse() to make your JSON into a proper Javascript object:
WidgetSvc.fetchWidgets().success(function(response){
var data = JSON.parse(response);
// now you can do
data[0].widget_discount = 10;
}

Deduplicating using nodeJS

My goal is to take in a CSV file which contains approximately 4 million records and process each record while scrubbing the data of a particular field. The scrubbing process we have actually creates a reversible hash but is a time consuming process (almost 1 second). What I would like to do since there are only about 50,000 unique values for that field is to set them as properties of an object. Here is a pseudo example of how the object will be built. You can see that for duplicates I plan to just overwrite the existing value (this is to avoid having to loop through some if based search statement.
var csv = require('csv');
var http = require('http');
var CBNObj = new Object;
csv()
.fromPath(__dirname+'/report.csv',{
columns: true
})
.transform(function(data){
CBNObj[data['Field Value']] = data['Field Value'];
});
console.log(CBNObj);
This should create my object something like this.
myObj['fieldValue1'] = 'fieldValue1'
myObj['fieldValue2'] = 'fieldValue2'
myObj['fieldValue3'] = 'fieldValue3'
myObj['fieldValue1'] = 'fieldValue1'
myObj['fieldValue1'] = 'fieldValue1'
I have looked over some good posts on here about iterating over every property in an object (like this one Iterating over every property of an object in javascript using Prototype?) but I am still not exactly sure how to acccomplish what I am doing. How can I then take my object with 50k properties and essentially dump the values into an array so that I can end up with something like this?
myArray = ['fieldVaue1','fieldVaue2','fieldVaue3']
EDIT: I could also use some assistance on the first part here because I am getting a null value or undefined when I try and set the object properties. I also still need help then traversing through the object properties to build my array. Any help would be greatly appreciated.
You know that the keys of your object are the unique values you want. You just need an array. In node.js you can use Object.keys().
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys
It's a standard way to take all the keys of an object (that aren't provided by the prototype chain) and put them into an array. So your example looks like this.
var csv = require('csv');
var AcctObj = new Object();
var uniqueArray;
csv()
.fromPath(__dirname+'/report.csv',{
columns: true
})
.on('data',function(data){
AcctObj[data['Some Field Value']] = data['Some Field Value'];
})
.on('end', function(){
uniqueArray = Object.keys(AcctObj);
});
Object.keys also does the hasOwnProperty check internally, so it's similar to the answer by #DvideBy0. It's just one step to the array you want.
var csv = require('csv');
var AcctObj = new Object();
csv()
.fromPath(__dirname+'/report.csv',{
columns: true
})
.on('data',function(data){
AcctObj[data['Some Field Value']] = data['Some Field Value'];
})
.on('end', function(){
for(var prop in AcctObj) {
if(AcctObj.hasOwnProperty(prop))
//Do something here....
}
});

Categories

Resources