AngularJS - stepping through array within the array - javascript

angular.forEach($scope.lista, function(data) {
console.log(data);
$scope.listaCliente = data.listaClienteMaquina;
console.log($scope.listaCliente);
});
being that when I access the array of $ scope.listaCliente, it returns undefined, someone help me? : /

being that when I access the array of $scope.listaCliente, it returns undefined
One thing I am sure of is if $scope.listaCliente is an array then you need to push into it. Currently you are reassigning it every-time your loop runs.
$scope.listaCliente.push(data.listaClienteMaquina);
I hope you also initialized the array outside like
$scope.listaCliente = [];

You are iterating all of the properties of the object $scope.lista instead of the array collection listaClienteMaquina.
You can test it here http://codepen.io/leandroh/pen/RPgvwP
Avoid $watch and use ng-change.
Details in this post http://www.benlesh.com/2013/10/title.html

Related

Javascript multi dimensional array issue

I want to create an array like this:
send[1]['conversation_group_id']=1;
But i get an error that cannot set property conversation_group_id of undefined. What am i doing wrong?
Thanks!
Even though you have initialized send with [], which makes it an array, send[1] will be undefined, you will need to initialize it as an object too before you can set a property inside it. At the moment you are trying to set a property of undefined.
var send = [];
console.log(send[1]);
send[1] = {};
send[1]['conversation_group_id']=1;
console.log(send[1]['conversation_group_id']);
Your data structure is an array of objects. To initialize it, you can also do it this way.
send = [null, {conversation_group_id: 1}]
Nothing wrong with #Dij's answer, but just though it's worth mentioning an alternative on how to initialize the structure you're looking for.

Cant access single object in array?

Hi I am having problems with accessing Object in array... I dont know is it because i updated Chrome or because i added, and after removed Preact from my React application. Problem is this:
Tags is array of objects:
var fullTag = tags.filter(tag => tag.tagId==tagId);
console.log(fullTag);
And as a result i get this in console:
[{…}]
When i expand it i get this:(image)
So there's no way to access it except with
console.log(Object(fullTag[0]).tag);
In all other ways i get undefined... Why is this?! I can swear that i could access it with fullTag.tag until yesterday... Can someone explain me please?
The filter() method creates a new array with all elements that pass the test implemented by the provided callback function.
So, after you filter an array, you will obtain another array even if there is only one item which pass the test function. That's why you couldn't access it using fullTag.tag.
Solution is to access one element using its index.
let tags=[{"id":1,"tag":"tag1"},{"id":2,"tag":"tag2"}];
let tagId=1;
var fullTag = tags.filter(tag => tag.id==tagId);
console.log(fullTag);
console.log(Object(fullTag[0]).tag);
If tagId property is unique in your array you can use find method.
var fullTag = tags.find(tag => tag.id==tagId);
Now you can access your tag property in that way you wished.
console.log(fullTag.tag);

Convert array of array objects into array of objects

I've spent the last couple hours going through some very similar answers to the above question but after a few implementations of loops and reduce I still have not gotten the solution I need.
I am getting an array of objects via service calls. I am pushing those controller array objects to another array because I need a single array to load data into a multi select. I.E.
StatesService.getAreaCities().then(function(response) {
controller.cities = response.data.rows;
controller.areaOptions.push(controller.cities);
});
StatesService.getAreaStates().then(function(response) {
controller.states = response.data.rows;
controller.areaOptions.push(controller.states);
});
controller.areaOptions = [];
This is an example of how I expect and need my array object to look.
With no modification this is how my array looks with those array objects pushed in.
How do I get the above data structure like the 1st image, an array of objects? I tried a solution with reduce()
var newCities = controller.cities.reduce(function(city){
return controller.city;
}, {});
controller.areaOptions.push(newCities);
but it wasnt what I was looking for because it returned a single object with all city property and all its values. I need each object to contain city and its value.
EDIT
I figured out the solution! Thanks to Lex.
I looped over each object in the array in each service and pushed the property.
Thanks to all for steering me in the right direction to figure this out, even the person that downvoted me :)
StatesService.getAreaCities().then(function(response) {
controller.cities = response.data.rows;
controller.cities.forEach(function(city){
controller.areaOptions.push(city);
});
});
Looks like response.data.rows is an array. So when you push response.data.rows into controller.areaOptions you are adding the rows array as an array element. (Basically making it a 2-dimensional array)
You should use Array.prototype.concat

How to access object of array?

I am new to jquery and trying something and got stuck at it,
My problem is i have object with array in it i am not able to find the way to access that array from the object
//My object is shown in debugging time is as below
cache:object
0001-:Array[2]
0:value1,
1:value2
_prto_:object
and i want to access the value1 and value2 from the 0001- array from that object is there way to access that array. Any help would be great. I know with $.each i can loop through it and and then again access the array but is there any other way to do it.
You can access it like, and keep in mind that you should use bracket notation in this context, since your keys having a starting character as a number.
cache['0001-'][0] //first element on that array
cache['0001-'][1] //second element
A workaround for your new requirement,
var cache = {'0001-' : [0,1]};
var xKeys = Object.keys(cache);
console.log(xObj[xKeys[0]][0]);
console.log(xObj[xKeys[0]][1]);

Javascript pushing objects into array changes entire array

I'm using a specific game making framework but I think the question applies to javascript
I was trying to make a narration script so the player can see "The orc hits you." at the bottom of his screen. I wanted to show the last 4 messages at one time and possibly allow the player to look back to see 30-50 messages in a log if they want. To do this I set up and object and an array to push the objects into.
So I set up some variables like this initially...
servermessage: {"color1":"yellow", "color2":"white", "message1":"", "message2":""},
servermessagelist: new Array(),
and when I use this command (below) multiple times with different data called by an event by manipulating servermessage.color1 ... .message1 etc...
servermessagelist.push(servermessage)
it overwrites the entire array with copies of that data... any idea why or what I can do about it.
So if I push color1 "RED" and message1 "Rover".. the data is correct then if I push
color1"yellow" and message1 "Bus" the data is two copies of .color1:"yellow" .message1:"Bus"
When you push servermessage into servermessagelist you're really (more or less) pushing a reference to that object. So any changes made to servermessage are reflected everywhere you have a reference to it. It sounds like what you want to do is push a clone of the object into the list.
Declare a function as follows:
function cloneMessage(servermessage) {
var clone ={};
for( var key in servermessage ){
if(servermessage.hasOwnProperty(key)) //ensure not adding inherited props
clone[key]=servermessage[key];
}
return clone;
}
Then everytime you want to push a message into the list do:
servermessagelist.push( cloneMessage(servermessage) );
When you add the object to the array, it's only a reference to the object that is added. The object is not copied by adding it to the array. So, when you later change the object and add it to the array again, you just have an array with several references to the same object.
Create a new object for each addition to the array:
servermessage = {"color1":"yellow", "color2":"white", "message1":"", "message2":""};
servermessagelist.push(servermessage);
servermessage = {"color1":"green", "color2":"red", "message1":"", "message2":"nice work"};
servermessagelist.push(servermessage);
There are two ways to use deep copy the object before pushing it into the array.
1. create new object by object method and then push it.
servermessagelist = [];
servermessagelist.push(Object.assign({}, servermessage));
Create an new reference of object by JSON stringigy method and push it with parse method.
servermessagelist = [];
servermessagelist.push(JSON.parse(JSON.stringify(servermessage));
This method is useful for nested objects.
servermessagelist: new Array() empties the array every time it's executed. Only execute that code once when you originally initialize the array.
I also had same issue. I had bit complex object that I was pushing in to the array. What I did; I Convert JSON object as String using JSON.stringify() and push in to the Array.
When it is returning from the array I just convert that String to JSON object using JSON.parse().
This is working fine for me though it is bit far more round solution.
Post here If you guys having alternative options
I do not know why a JSON way of doing this has not been suggested yet.
You can first stringify the object and then parse it again to get a copy of the object.
let uniqueArr = [];
let referencesArr = [];
let obj = {a: 1, b:2};
uniqueArr.push(JSON.parse(JSON.stringify(obj)));
referencesArr.push(obj);
obj.a = 3;
obj.c = 5;
uniqueArr.push(JSON.parse(JSON.stringify(obj)));
referencesArr.push(obj);
//You can see the differences in the console logs
console.log(uniqueArr);
console.log(referencesArr);
This solution also work on the object containing nested keys.
Before pushing, stringify the obj by
JSON.stringify(obj)
And when you are using, parse by
JSON.parse(obj);
As mentioned multiple times above, the easiest way of doing this would be making it a string and converting it back to JSON Object.
this.<JSONObjectArray>.push(JSON.parse(JSON.stringify(<JSONObject>)));
Works like a charm.

Categories

Resources