Assigning multiple indices at once from one list [duplicate] - javascript

This question already has answers here:
JavaScript Object Literals & Array Literals
(4 answers)
Closed 5 years ago.
I have five user variables with different names. I'd like them to end up in an array, and am wondering if I can do the assignment to multiple array indices in a single line. Currently, if I do this
var users = {user5k, user10k, user15k, user20k, user25k};
I can't index it later (says users[0] is undefined). So I want the indices built in to the assignment. Something along these lines:
var users = {};
users[0:4] = {user5k, user10k, user15k, user20k, user25k};
This doesn't seem possible in JavaScript, meaning I have to do this:
var users = {};
users[0] = user5k;
users[1] = user10;
// ... et cetera
Is there a way to accomplish the first solution?

When you use {} you're creating an object, not an array. Use [] for arrays.
var users = [user5k, user10k, user15k, user20k, user25k];
If you want to replace part of an array that already exists, you can use Array.prototype.splice()
var users = [];
users.splice(0, 4, [user5k, user10k, user15k, user20k, user25k]);

Related

Why does it change the array(argument) value in a function, when I already passed the array(argument) values to another one to modify? [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 3 years ago.
So I need the original(argument) array to stay the same, AND have another array (array2) with it's values to make some changes on it but mantain the original(argument) array intact.
Example:
let wtf = function(array){
let array2 = array
array2[0] = array2[0].replace(array2[0][0],"1")
console.log( array + " " + array2)
}
wtf(["a","b"])
Result in console:
1,b 1,b
BUT I need a,b 1,b
(that comes from: array = a,b and array2 = 1,b )
Thanks!
I think this is a reference value vs a clone value problem.
With your let array2 = array line, I think you're creating a reference to the same in-memory object, so you're actually modifying a single array twice, even though it looks like you've created another one.
To create a 'true' clone you can try something like:
let array2 = JSON.parse(JSON.stringify(array));

Struggling with Javascript Object Array adding keys [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 5 years ago.
I have this snippet of code:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
arrLiteData.push({ii:{"field1":100,"field2":ii}});
}
...but instead of ii taking the increasing numeric value of ii, the array just holds the actual variable name, like this:
[{"ii":{"field1":100,"field2":0}},{"ii":{"field1":100,"field2":1}}...etc, etc...
What am I doing wrong?
Many thanks.
Quotes are optional for javascript object keys, so
{ii:{"field1":100,"field2":ii}} is the same as
{"ii":{"field1":100,"field2":ii}} or even
{ii:{field1:100,field2:ii}}. They are just need if you have non alphanumeric characters.
To solve this you could either use a computed key if you're transpiling your code or targeting recent navigators:
{[ii]:{"field1":100,"field2":ii}}
Or build the object in two steps:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
var obj = {};
obj[ii] = {"field1":100,"field2":ii};
arrLiteData.push(obj);
}

Javascript: how to join two arrays [duplicate]

This question already has answers here:
Javascript Array Concat not working. Why?
(7 answers)
Closed 6 years ago.
I know this has been asked a lot of times, but I cannot get it to work.
I have an empty array a
var a = [];
and an array with an object b
var b = [{
title: 'test'
}]
I want to join them so a will look exactly like b.
The idea is to do this inside a for loop so a would be added a new item each time.
By using a.concat(b), a results in an empty array.
Not sure what I am missing.
Per Array.prototype.concat()
This method does not change the existing arrays, but instead returns a new array.
You need to assign this operation back to a
a = a.concat(b)
You need to assign result of that call to a. a = a.concat(b)

Javascript - array connect to another [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
When I assign a variable to another variable does it not link them together?
(1 answer)
Closed 9 years ago.
I have really weird situation:
when I do that code:
var origin_array = [1,2,3];
var m = origin_array;
m.pop();
alert(origin_array);
origin_array value will be 1,2
eventhough I didn't changed it
but if I make that code:
var x = 5;
var y = x;
y--;
alert(x);
x still be 5, it won't be connected to "x" as you can see from the 1st example.
So my question is how do I make the "m" array unique, which not change the origin array?
You need to explicitly make a (shallow) copy or clone of origin_array:
var m = origin_array.slice(0);
This is not needed for primitive values, such as strings and numbers.
It's important to understand that although the above will prevent the issue you were experiencing, the same may happen again deeper down if you're dealing with more complex structures, and in some cases a "deep clone" is necessary.
Arrays are assigned by reference. That means that when you do this:
var origin_array = [1,2,3];
var m = origin_array;
m just points to the exact same array as origin_array. There is only one array and both origin_array and m point to it. If you modify it via either variable, they will both see the modification because you're modifying the one array that they both point to.
In javascript, both objects and arrays are assigned by reference like this. Assigning them does NOT make a copy. If you want an assignment to generate a copy, you have to explicitly make a copy. For an array, that is easy as you can just do:
var origin_array = [1,2,3];
var m = origin_array.slice(0); // makes a shallow copy
m.pop();
console.log(origin_array); // [1,2,3] because origin_array was not changed

How to change the given below json array? [duplicate]

This question already has answers here:
Extract each value of a single property from an array of objects in jQuery
(5 answers)
Closed 9 years ago.
I have a JSON array in the following format:
[{"country":"Algeria"},{"country":"Africa"},{"country":"America"},{"country":"Libiya"}]
I need to change it as follows:
{"Algeria","Africa","America","Libiya"}
How do I do that using Jquery or JavaScript?
In javascript:
var myArray = [{"country":"Algeria"},{"country":"Africa"},{"country":"America"},{"country":"Libiya"}];
var myNewArray = [];
for (var item in myArray) {
var country = myArray[item].country;
myNewArray.push(country);
}
alert(JSON.stringify(myNewArray));
You're actually have the wrong notation in your question. The end result you want should have square brackets ([]), not curly braces({}). Curly braces indicate an object instead of an array but you are not using a key-value structure so the end-result you have above is actually invalid.
Instead it seems you want ["Algeria","Africa",America","Libiya"] as the end-result.
Assuming you mean literally changing the array you have rather than creating a new one and assuming you are using JavaScript:
var arr = [{"country":"Algeria"},{"country":"Africa"},{"country":"America"},{"country":"Libiya"}], // declare your array upfront (but this could be a `JSON.parse()` call)
i = 0, // counter
l = arr.length; // limit/length of array
for (i; i < l; i += 1) {
arr[i] = arr[i].country; // Replace object with value of country property.
}
// `arr` will now be `["Algeria","Africa",America","Libiya"]`
Of course you might want to introduce some checks to ensure that every element of the array has a property called country and some way to deal with that in the rewritten array. But I'll leave you with this for now, see how you get on. This should work if your array is valid to begin with.

Categories