Angular / Javascript search array for object key - javascript

For the purpose of example lets have the following object:
var myobj = {id: 1, text: 'hello world', user_id: 5}
Now lets say we have an array:
var objectContainer = []
And we fill this objectContainer with x number of myobj
Now we wish to find the myobj that has the id value set to 30
You could use a loop but in worst case you would have to loop through the whole array before finding your value.
So my question is does JaVaScript have a function for these situations or does AngularJsprovide additional helpers to solve this?

You have a lot of different solutions :
Javascript FIND : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Example :
var myobject = objectContainer.find(function(value){ return value.id === 1; });
Angular filter : https://docs.angularjs.org/api/ng/filter/filter
If your ids are unique you could also use a map instead of an array :
Exemple :
var myobj = {id: 1, text: 'hello world', user_id: 5};
var objectContainer = {};
objectContainer[myobj.id] = myobj;
etc

Your value of 'x' is the array indexer. So objectContainer[29] should point to the myobj in the 30th position.

Also you can use my solution of finding objects in an array.
But still it will loop over all elements of an array.

Related

How to create an associative array in JavaScript literal notation

I understand that there are no associative arrays in JavaScript, only objects.
However I can create an array with string keys using bracket notation like this:
var myArray = [];
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray); // Prints [a: 200, b: 300]
So I want to do the exact same thing without using bracket notation:
var myNewArray = [a: 200, b: 300]; // I am getting error - Unexpected token:
This does not work either:
var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?
JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).
So look at your code first:
var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300
It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!
So to start with what you want:
You can't create a JavaScript array and pass no number attributes to it in one statement.
But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.
You can use Map:
var arr = new Map([
['key1', 'User'],
['key2', 'Guest'],
['key3', 'Admin'],
]);
var res = arr.get('key2');
console.log(res); // The value is 'Guest'
You want to use an object in this case
var myObject = {'a' : 200, 'b' : 300 };
This answer links to a more in-depth explanation: How to do associative array/hashing in JavaScript
Well, you are creating an array, which is in fact an object:
var arr = [];
arr.map;
// function(..)
arr['map'];
// function(..)
arr['a'] = 5;
console.log(arr instanceof Object); // true
You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).
You can refer to an object fields with the [] syntax.
I achieved this by using objects. Your create an object, and loop through using for in loop. each x will be the index and holder[x] will be the value. an example is below.
var test = {'hello':'world','hello2':'world2'}
for(let x in holder)
{
let inxed = x;
let value = holder[x]
console.log('index ' + x + ' has value of ' + value)
}
Associate array is an array indexed with name similar to an object instead of numbers like in regular array. You can create an associative array in the following way:
var arr = new Array(); // OR var arr = [];
arr['name'] = 'david'
arr['age'] = 23;
console.log(arr['name']);
You can do what you wanted to do this way:
myNewArray = new Array ({'a' : 200, 'b' : 300})

An object contains a collection of objects - each with an id and name, how do I separate them?

At the moment I have this object:
obj = [object{id: 1, name: test, parentID: 3}, object{id:1, name: another, parentID: 5}, object{id:2, name:something, parentID: 1}].
Ultimately I want an object structured in a different manner.
So that it is object, but if my identifier is 1, it has a collection of names (in this case test, and another). If it is 2, it only shows 'something'.
I can't work out how this should look, probably like so?
obj = [[1,test], [1,another], [2,something]] right?
So that if I call obj[1] I get a multiples back (test, another etc).
Can someone help? I've been fiddling with this for an hour now, I just don't understand.
I built the original object like this:
var obj = Array();
//loop here
var obj = {
id: id,
name: name,
parentID: parentID
};
obj.push(obj);
What did I do wrong? How can I fix this? This got me my object within objects thing, but really I want id's and names within id's and names. My ultimate goal is to iterate through this. So that I only get out the names of anything of a like ID, that way I can use this to populate an array or count
Thus:
if(obj[id] == 1){
//put the name in the new array
}
is my ultimate goal. But I've gotten a bit lost with the initial object creation so now it is a big mess.
Try:
var obj = [{id: 1, name: "Foo"}, {id: 2, name: "Fee"}, {id: 3, name: "Fii"}];
var result = [], item, i = 0;
while(item = obj[i++]){
for(key in item){
if(key === "id") continue; //remove this line if you want to keep the ID also in the array
!result[i] && (result[i] = []);
result[i].push(item[key]);
}
}
console.log(result[1]); // --> ["Foo"]
My take:
var sourceObject=[{id:0,name:'Tahir'},{id:0,name:'Ahmed'},{id:1,name:'David'},{id:1,name:'G'},{id:2,name:'TA'},{id:3,name:'DG'}];
function getNames(id){
var names=[],length=sourceObject.length,i=0;
for(i;i<length;i+=1){
if(sourceObject[i].id===id){
names[names.length]=sourceObject[i].name;
}
}
return names;
}
console.log(getNames(1));
What you want to do is walk the array of objects one time. Each time through, you want to check your new object to see if that id exists yet. If it does, add the name. If not, make a new entry for that id and add an array with one entry. Note, this doesn't handle duplicate names (it just adds it again).
var array = [{id:1, name:"test"},
{id:1, name:"another"},
{id:2, name:"something"}];
var result = {};
array.forEach(function(item) {
if (result[item.id]) {
result[item.id].push(item.name);
}
else {
result[item.id] = [item.name];
}
});
console.log(result[1]);

Learning to programming JavaScript, but I'm stuck

Yesterday I started learning JavaScript. I am using the system Codecademy, but I'm stuck. When I say "stuck", I mean I have assignment with which I cannot see what is wrong.
The assignment is:
Create an array, myArray. Its first element should be a number, its second should be a boolean, its third should be a string, and its fourth should be...an object! You can add as many elements of any type as you like after these first four.
This is the code I made:
var myObj = {
name: 'Hansen'
};
var myArray = [12,true, "Steen" ,myObj.name];
The error:
Oops, try again.
Is the fourth element of myArray an object?
Hope you can help me.
The problem with your fourth element is you are passing a string because myObj.name is defined as Hansen. Pass the object instead:
var myArray = [12,true, "Steen" ,myObj];
I don't know that site, but you can do:
var myArray = [
12,
true,
"Steen",
{name: 'Hansen'}
];
What you are passing to the array is the value of the name property of your object instead of the object itself.
Your passing in the name property instead of the object for the fourth array parameter as you probably already know from the other anwers.
As your learning here are a few ways to do exactly the same thing as your accomplishing here.
Your way corrected:
var myObj = {
name: 'Hansen'
};
var myArray = [12, true, "Steen", myObj];
Other ways:
// Method 1
var myArray = [12, true, "Steen", {name: 'Hansen'}];
// Method 2
var myObj = new Object();
myObj.name = "Hansen";
var myArray = new Array(12, true, "Steen", myObj);
// Method 3
var myObj = {};
myObj['name'] = 'Hansen'
var myArray = [
12, true, 'Steen', myObj
]
Each method shows a few different ways to do the same thing, you can mix and match the equivalent parts of code to get the same job done. It's basically inter changing between the normal JavaScript syntax and object literal syntax.

Working with Java Script and multidimensional arrays

I am currently working on a website type project and I am new to JavaScript. So I have been having troubles with some parts of the syntax. Basically I am trying to print the 'id' and 'value' in the nested array arr.
var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})};
var obj = myArray[0];
document.write(obj.id);
this will print the id 1 but im not sure how to access id 10.
Also if there is an easier way to do this let me know please!
Firstly, don't use the new Array constructor. Just define an array literal [...]. So your myArray will look like:
var myArray = [{id:'1', value:'een', arr: [{id:'10', value:'een'}]}];
To get to the id of 10, you need to access myArray[0].arr[0].id;.
Proper reference would be:
obj.arr[0].id
PS: google chrome developer console is a goot playground for testing javascript object dereefrecing
You can't without iterating over the array.
If order does not matter, use an object instead:
var myObject = {
1: {id:'1', value:'een'},
10: {id:'10', value:'een'}
};
var obj = myArray[10];
document.write(obj.id);
In case the nesting in your array is intended, here's what you want:
var obj = myArray[0].arr[0];
Demo:
> var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})});
> myArray[0].arr[0]
{ id: '10', value: 'een' }
I would for get arrays why not create your own object ?
http://www.w3schools.com/js/js_objects.asp

Javascript defining array. "arrayception"

I am trying to create a list of "items" in a canvas game. For example, an array named list. Each element must contain the information about each item. First element will contain something different. I will remove first one with 'shift()' command. Like :
list.shift();
list[0]['name']
list[0]['id']
list[0]['x']
list[0]['y']
list[1]['name']
list[1]['id']
list[1]['x']
list[1]['y']
but i don't know how to define something like this. normally i define arrays like
{"name" : xx, "id" : 5 ... }
but this works like :
list['name']
list['id']
use:
var list = [];
list[0] = {name: 'xx', id: 0, /*etc*/};
list[1] = {name: 'yy', id: 1, /*etc*/};
it creates an array of objects. You can use it like this:
var first = list.shift();
first.name; //=> xx
//or
var first = list[0];
first.name; //=> xx
Note: using {...} (Object literal) creates an Object, not an Array. An array can be created using an Array literal: [...]. Although an object is sometimes said to be an Associative Array, it is not an Array object, so things like {...}.shift() will not work for Objects.
There are no associative arrays in javascript.
so for instance , when you do
var _array = []
_array["field1"] ="value";
you are actually adding a property to the _array object .
_array.field1 = value <=> _array["field1"] ="value";
so if you want to create a collection of objects , do
var collection =[];
var myObject = {"field1":"value1"};
collection.push(myObject);

Categories

Resources