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.
Related
Basically I have a complex object that retrieves the GPT API (google publisher tag) with this function:
googletag.pubads().getSlots();
The object value is something like this:
I need to know if there is a way to compare the value of each property with an X value without getting a problem of recursivity (because the object is huge and i need to to that validation several times)
Also, I tried to convert that object into a JSON with JSON.stringify(), and then tried to get the value with a regex, faster, but with this option, I have the problem with Cyclic Object Value.
Any suggestions ?
it's more simple. try it to convert it into an array and later use a filter for comparative with your value.
var objGoogle = {};
var arrayObjectGoogle = [objGoogle];
var filter = arrayObjectGoogle.filter(function(obj){
obj.yourAttr == yourValue; });
this will give you a second array with the values found it. later, index the array for pick up the value do you need.
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);
I have a form that uses $scope.booking variable composed of several fields and array, all loaded from HTML.
I need to add an array of object from javascript, adding one object per time.
I tryed
$scope.booking.newExternalUsers[$scope.count]= $scope.user.newExternalUser;
and
$scope.booking.newExternalUsers.push=$scope.user.newExternalUser;
but I receive Cannot set property '0' of undefined and Cannot set property of undefined, it is correct because I have instantiated only $scope.booking={}
Maybe is a stupid question, but I am almost new in angularjs, how can I add the $scope.user.newExternalUser one pertime (for each button event)?.
Thanks
You should define the array first before set values to it.
like this:
$scope.booking = {};
$scope.booking.newExternalUsers = [];
or
$scope.booking = {
newExternalUsers: []
};
Then
You can add items to it as you want, like this:
$scope.booking.newExternalUsers[$scope.count]= $scope.user.newExternalUser;
or using Array.prototype.push()
$scope.booking.newExternalUsers.push($scope.user.newExternalUser);
First define the property newExternalUsers in booking array first
$scope.booking={
'newExternalUsers' : []
}
or
$scope.booking.newExternalUsers=[]
Then push the item to an booking array
$scope.booking.newExternalUsers.push($scope.user.newExternalUser);
You have to instantiate $scope.booking.newExternalUsers=[]
I'll assume you have a controller. In that controller you can have this:
$onInit() {
this.booking = { newExternaUsers: [] };
}
Then it's initiated once when the controller starts.
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
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.