Arr.push inside For-loop - javascript

I have a SPA built with Vue and I'm trying to fetch an array of items from a custom API.
Once I've stored the items I'm trying to loop through that array and push in a custom path value, however I get the error
this.list[i].push is not a function
I'm not sure why this wouldn't be possible, but I'm sure I've missed something.
this.list: []
fetch(){
let url = 'http://core.com/api/v0/sources/'
axios.get(url).then((response) => {
this.list = response.data.data
for(var i = 0; i < this.list.length; i++){
let arr = { path: '/testPath' }
this.list[i].push(arr)
}
})
}

In the comments you mentioned your goal:
"this.list[i].path does not exist, that is what Im trying to create"
...if you literally want to add a property called "path" directly under the object at this.list[i] then you'd write
this.list[i].path = '/testPath'
This will create a new property for the object being held at this.list[i].
P.S.
You don't need your (badly-named) arr variable at all here.
Using .push() doesn't make any sense (and doesn't work) because this.list[i] contains an object rather than an array, and also doing that wouldn't create a property as you wanted.

push is the function of an array but you are trying to push an object in an object that's why you got this exception.
you can do as below.
this.list[i].path = '/testPath'
path property will be dynamically added in your object this.list[i].

Related

Why push does not working with set methond in Map object

So very quick question here which I wasn't able to get sorted when searching google.
I have some code that works which has a Map object this.tweet and a (key,value) of (string,array). I push a value into the array and re-set Map object.
const newTweet = this.tweet.get(tweetName) || [];
newTweet.push(time);
this.tweet.set(tweetName, newTweet);
However, I am a minimalist freak and want a one-liner. When I want to add something to the array, I was wondering why I am not able to do this
this.tweet.set(tweetName, newTweet.push(time));
I keep getting a newTweet.push(time) is not a function error.
Thanks
Look at some documentation for push
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Since you want to pass the array to set you can't use the return value of push.
You could create a completely new array instead:
const newTweet = this.tweet.get(tweetName) || [];
this.tweet.set(tweetName, [...newTweet, time]);

JavaScript Object giving different values when accessed directly

I am using React.js and I'm trying to update the state of my component when the props change. Before I explain the problem, I should mention that I have used both getDerivedStateFromProps and componentDidUpdate, the result is the same. The problem is that when I try to access the value of an element in prop, it differs whether I access the value directly or I use the object itself.
let userTickets = nextProps.support.userTickets;
// userTickets[0].messages is different from nextProps.support.userTickets[0].messages
below is the whole function code.
let userTickets = nextProps.support.userTickets;
console.log(nextProps.support.userTickets); // this contains the correct, updated value
for (let index = 0; index < userTickets.length; index++) {
let userTicket = userTickets[index];
console.log(userTicket); // this contains old incorrect value
}
Any guidance would be appreciated. Thanks.
Try to not directly assign props to variables because it may assign by reference instead of copy. Try this instead:
const userTickets = [ ...nextProps.support.userTickets ];
console.log(nextProps.support.userTickets);
userTickets.map(ticket => {
console.log(ticket);
});
Notice the 3 dot assignment of the array, this creates a new array with the values of the array that is "spread"

Javascript / Node Js - Create New variable for each instance

I'm creating a game bot on telegram using node js.
Currently I'm facing a problem on shared variable (module.exports). I'm storing some of the data on the variable. And the problem is, the shared variable index always change. For example, please refer to my code below
var sharedVar = [];
createNewRoom = function(res) {
var index = sharedVar.length;
sharedVar.push({ groupId : res.chat.id }); // every time this function is invoked, it will create a new array inside sharedVar object
//Here comes the problem, it's about the index,
//because I'm using sharedVar to store arrays, then it will become a problem,
//if one array is deleted (the index will change)
var groupId = sharedVar[index].groupId; // it runs OK, if the structure of array doesn't change, but the structure of array change, the index will be a wrong number
}
As you can see, i got callGameData function, when i call it, it will show the last value of sharedVar, it's supposed to show the current room values / data.
As i mention on the code above, it's all about the dynamic array in the sharedVar object, the index will change dynamically
Any thoughts to tackle this kind of issue? I was thinking about using a new sharedVar object everytime the createNewRoom function is invoked, but the thing is, i have to use sharedVar in many different function, and i still can't figure it out on using that method.
EDIT
This is the second method
var gameData = undefined;
createNewRoom = function() {
this.gameData = new myConstructor([]); // it will instantiate a new object for each new room
}
myConstructor = function(data) {
var _data = data;
this.object = function() {
return _data;
}
}
callGameData = function() {
console.log(gameData);
}
An array is fundamentally the wrong data type to use if you want to keep indices the same even in the face of removing entries.
A better method is to use properties of an object. For example:
var roomCache = { nextId: 1 };
createNewRoom = function(res) {
roomCache[roomCache.nextId++] = {groupId: res.chat.id}; // Add a new object to the cache and increment the next ID
}
After adding two elements, you'll have the rooms in roomCache[1] and roomCache[2] - if you want to start at zero just change the original value of nextId. You can delete elements in this object and it won't shift any keys for any other objects - just use delete roomCache[1] for example to get rid of that entry.
This assumes there isn't a better ID out there to use for the cache - if, for example, it made more sense to lookup by res.chat.id you could certainly use that as the key into roomCache rather than an auto-incrementing number. Here's how it would look like to cache the values by the group ID instead:
var roomCache = { };
createNewRoom = function(res) {
roomCache[res.chat.id] = {groupId: res.chat.id}; // Assumes res.chat.id is not a duplicate of an already cached obhect
}
Now you could just look up by group ID in the cache.
Yes, it's definitely a problem cause you are not keeping track of the index in a logical way, you are relying on position on the array which it changes, you need something that doesn't change over time to keep consistency and supports deletition of the element without affecting the rest of the elements. You could use mongo to store the generated rooms by id or maybe redis or some kind of key value pair database to store that kind of information.

Delete property of an array object using javascript

I have an array object in the below format and need to delete a property of an array.
Code:
var partDetailArray={[PartId:100,PartRowID:'row-1']
,[PartId:100,PartRowID:'row-1']};
delete partDetailsArray.PartRowID;
I need to remove the PartRowID property from the array, but the delete statement isn't working.
If you look in the console, you'll see that you're getting syntax errors with that code for the reasons I put in my comment on the question.
I'm going to guess you meant to have an array containing objects, like this:
var partDetailArray = [
{PartId:100,PartRowID:'row-1'},
{PartId:100,PartRowID:'row-1'}
];
In that case, the array doesn't have a PartRowID property, but each of the objects in it does. So we need to index into the array to access the object, and delete the property from it:
delete partDetailsArray[0].PartRowID;
// Indexing into it ---^^^
That would delete that property from the first one. If you want to delete all of them, you'll need a loop:
var index;
for (index = 0; index < partDetailArray.length; ++index) {
delete partDetailsArray[index].PartRowID;
}

creating objects in for loop javascript

I hope you can help me with this hopefully stupid problem.
I try to do the following:
creating array with data
looping through this array within a for loop (based on array.length)
create new object based on data in array
So far I got the following:
create array
loop through array
create one object based on my constructor
The problem is, the array has a length of 4 and should therefore create 4 objects but it creates only one. If I remove the creation of the object and just log "i' it works, but in the original intention it ends after the first
The loop looks as follows:
for(i=0;i<array.length;i++)
{
newObj[i]=new ObjectName(array[i].param1,array[i].param2,array[i].param3)
}
I have no idea why it ends after the first run and I also don't get an error displayed when looking into firebug.
Cheers
Does changing the
newObj[i] =
to
newObj.push(...)
help?
Also how is newObj initialized?
newObj = []
for (i = 0; i < (stringNums.length); i++) {
Dictionary[stringNums[i]] = stringNums[i].length;
}

Categories