angularjs : iterate array with key value pairs - javascript

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

Related

javascript merge to array with name

I am new in JS. It is a simple task but find it is hard to solve. I tried many methods includingconcat,push,$.merge
Here is an example
var a=[]
var b=[]
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"
I want to get a result like [a:"b", c:"d", e:"f", g:"h"],
Here is some method I have tried
a.concat(b)get []
a.push(b) get 1
$.merge(a,b) get [0:[e:"f", g:"h"],a:"b",c:"d"]
I don't know where to go, Please help
The biggest problem you're running into right now is that you are trying to use an array as an object, so first when you're initializing a and b you should use curly braces instead. And then to merge them, you can use the spread operator: ....
All of that culminates into this:
let a = {};
let b = {};
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"
a = {...a, ...b}
You cant get an array with key-value pairs its an invalid syntax, but you can create an object. Just spread both of your objects into an single object:
var a=[]
var b=[]
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"
let result = {...a,...b};
console.log(result);

How to store number of object element of array in another array?

im trying to store some object element from one array to another so lets say i have this array of objects
var Array = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
and i want to store the first two object in this array to another array so it would like be
var SubArray =[{name:'Fadi'},{name:'Joseph'}];
thanks in advance for any help.
You can use slice method for this:
var SubArray = Array.slice(0,2);
Please note that Array is reserved JS global object. You need to use different name for that variable. So your code should be for example:
var MyArray = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
var SubArray = MyArray.slice(0,2);
If you need conditional logic you want Array.filter(). If you know you always want the items by index then use slice as in antyrat's answer.
var originalArray = [{name:'Fadi'},{name:'Joseph'},{name:'Salim'},{name:'Tony'}];
var subArray = originalArray.filter(function(obj,index) {
return obj.name=="Fadi" || obj.name=="Joseph";
})

Concatenating html object arrays with javascript

I'm attempting to merge two arrays made up of html objects. For some reason using .concat() will not work for me.
Here's a simple pen to demonstrate the problem: http://codepen.io/anon/pen/kIeyB
Note: I tried searching for something remotely similar but found nothing that answered my question.
I figure you can do this the ole fashion way using for-loops but I rather not re-invent the wheel.
var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
//alert(items.length);
var items2 = x.getElementsByClassName("two");
//alert(items2.length);
items = items.concat(items2);
//alert(items.length);
items and items2 are nodeList or HTMLCollection objects, not arrays. They do not contain a .concat() method. They have a .length property and support [x] indexing, but they do not have the other array methods.
A common workaround to copy them into an actual array is as follows:
// convert both to arrays so they have the full complement of Array methods
var array1 = Array.prototype.slice.call(x.getElementsByClassName("one"), 0);
var array2 = Array.prototype.slice.call(x.getElementsByClassName("two"), 0);
This can be also be done like this:
var allitems = [];
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("one"));
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("two"));
The allitems variable will be a single javascript Array containing all elements with class one & two.
What you have are HTMLCollections, which although behave like arrays, but are not arrays. See here: https://developer.mozilla.org/en/docs/Web/API/HTMLCollection:
..A collection is an object that represents a lists of DOM nodes..
In your case, you could concatenate these objects together into a new array:
var itemsnew;
var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
var items2 = x.getElementsByClassName("two");
itemsnew = Array.prototype.concat.call(items, items2);
Now, if you:
console.log(itemsnew);
Will return:
[HTMLCollection[1], HTMLCollection[1]]
And:
console.log(itemsnew[0][0]);
Will return:
<div class="one"></div>
document.getElementsByClassName doesn't return an array.
It returns NodeList which has length property.

Creating Nested Objects on the Fly With 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.

Test for value within array of objects

I am dynamically building an array of objects using a process that boils down to something like this:
//Objects Array
var objects = [];
//Object Structure
var object1 = {"id":"foobar_1", "metrics":90};
var object2 = {"id":"some other foobar", "metrics":50};
objects[0] = object1;
objects[1] = object2;
(Let it be said for the record, that if you can think of a better way to dynamically nest data such that I can access it with objects[i].id I am also all ears!)
There's ultimately going to be more logic at play than what's above, but it's just not written yet. Suffice it to say that the "object1" and "object2" parts will actually be in an iterator.
Inside that iterator, I want to check for the presence of an ID before adding another object to the array. If, for example, I already have an object with the ID "foobar_1", instead of pushing a new member to the array, I simply want to increment its "metrics" value.
If I wasn't dealing with an array of objects, I could use inArray to look for "foobar_1" (a jQuery utility). But that won't look into the object's values. The way I see it, I have two options:
Keep a separate simple array of just the IDs. So instead of only relying on the objects array, I simply check inArray (or plain JS equivalent) for a simple "objectIDs" array that is used only for this purpose.
Iterate through my existing data object and compare my "foobar_1" needle to each objects[i].id haystack
I feel that #1 is certainly more efficient, but I can't help wondering if I'm missing a function that would do the job for me. A #3, 4, or 5 option that I've missed! CPU consumption is somewhat important, but I'm also interested in functions that make the code less verbose whether they're more cycle-efficient or not.
I'd suggest switching to an object instead of an array:
var objects = {};
objects["foobar_1"] = {metrics: 90};
objects["some other foobar"] = {metrics: 50};
Then, to add a new object uniquely, you would do this:
function addObject(id, metricsNum) {
if (!(id in objects)) {
objects[id] = {metrics: metricsNum};
}
}
To iterate all the objects, you would do this:
for (var id in objects) {
// process objects[id]
}
This gives you very efficient lookup for whether a given id is already in your list or not. The only thing it doesn't give you that the array gave you before is a specific order of objects because the keys of an object don't have any specific order.
Hmm , i wonder why dont you use dictionary cause that is perfectlly fits your case. so your code will be as below:
//Objects Array
var objects = [];
//Object Structure
var object1 = {"metrics":90};
var object2 = {"metrics":50};
objects["foobar_1"] = object1;
objects["some other foobar"] = object2;
// An example to showing the object existence.
if (!objects["new id"]){
objects["new id"] = {"metrics": 100};
}
else {
objects["new id"].matrics++;
}

Categories

Resources