How can I get an object inside an array in JavaScript? [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I have a for loop and I would like to tap into an object inside the array I am looping. Specifically I would like to tap into the "Name" section of my objects to only console.log the names, not the whole array. This is the code... I am doing this with Mongoose but I don't think it has anything to do with my problem, I just wanted to add it tho.
const newCustomerNum2 = new customerList({
name: "John",
age: 32
});
customerList.find(function(err, customers) {
if (err) {
console.log(err);
} else {
for (var i = 0; i<customers.length; i++){
console.log(customers.name);
}
}
});

What is happening in your for loop, is that you are looping over the indices of your array.
Let's say you array has 3 elements, the for loop would be called with i = 0, then i = 1, then i = 2.
This index can be used to reference an object in your array.
When you are calling customers.name you are trying to access the property name on the array rather than the data in it.
If you want to access the objects inside your array, use the subscript expression:
customers[i] where 0 < i < customers.length.
That way, you can use console.log(customers[i].name) in your loop.
In addition, you could simply use the for ... of expression, which iterates over the elements of an array:
for (let customer of customers) {
console.log(customer.name);
}

Related

Use a loop to give array items an eventListener with a function with an unique parameter [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 1 year ago.
I'm creating a small project where there are many buttons with the same class calling the same function. I've pushed them into an array using a loop.
Now, depending on the button the user presses, it should call said function, and also pass an unique parameter based on its array index.
So basically, I want to create a loop that gives all the same-classed buttons an eventListener to call the function, but with a different parameter.
This is what i've tried:
let CTAs = []
for(i = 0; i < document.getElementsByClassName("CTAenabled").length; i++) {
CTAs.push(document.getElementsByClassName("CTAenabled")[i])
CTAs[i].addEventListener("click", () => {myFunction(i)})
}
function myFunction(n) {
console.log(n)
}
Using this loop, all buttons are properly pushed into the array, but when pressed, they all pass the same parameter, making the function print the same number.
Any ideas on how to give each button a different parameter according to its index?
Perhaps you could define an array outside of the loop that stores the values needed for the function parameter. These could be accessed with the value of i in your loop. They could also be dynamically generated in a separate for loop if needed.
let CTAs = []
let otherVals = [val1, val2, val3]
for(i = 0; i < document.getElementsByClassName("CTAenabled").length; i++) {
CTAs.push(document.getElementsByClassName("CTAenabled")[i])
CTAs[i].addEventListener("click", () => {myFunction(otherVals[i])})
}
function myFunction(n) {
console.log(n)
}

Why when I update a nested array in the parent array and other children receive the same value? [duplicate]

This question already has answers here:
Strange behavior of an array filled by Array.prototype.fill()
(9 answers)
Array.prototype.fill() with object passes reference and not new instance
(7 answers)
Modifying a copy of a JavaScript object is causing the original object to change
(13 answers)
Closed 1 year ago.
I faced a strange situation when I tried to create an array of arrays via fill and then I tried to add some value to the first child I saw all other nested arrays receive this value as well.
I have an idea why it could happen. It looks like the fill property uses the same object of all 3 nested 'places\items' and now each item is the reference to the single Array.
Also, I tried to use the .fill(new Array()) instead of the literal expression but I had the same result.
I'm not sure if I'm right so fix me, please, if I missed something. Thanks
// an amount of the required output arrays
const requiredArrays = 3;
const cols = new Array(requiredArrays).fill([]);
cols[0].push({id: 1})
The expected result:
[
[
{
"id": 1
}
],
[],
[]
]
the actual result:
[
[
{
"id": 1
}
],
[
{
"id": 1
}
],
[
{
"id": 1
}
]
]
P.S. What is the right way to achieve the result I want to have? Should I just use the for cycle and populate the parent array via the children or maybe some nicer way exists?
From the fill docs at MDN:
If the first parameter is an object, each slot in the array will reference that object.
This means that you get an array of references to the same array (which is an object as well).
As to how to do it in a nicer way... that depends on what you want to achieve. Why do you need the array of arrays? Will they all have a fixed length?
Arrays are passed down by reference this makes it not that great for the fill method. Though you can fill it with a placeholder value and then map those to an array.
const requiredArrays = 3;
const cols = new Array(requiredArrays).fill('').map(() => []);
cols[0].push({id: 1})
console.log(cols);
EDIT: As pointed out in the comments, a better solution:
const requiredArrays = 3;
const cols = Array.from({length: requiredArrays}, () => []);
cols[0].push({id: 1})
console.log(cols);

How to get every value in Json by key in Javascript [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 5 years ago.
I am making a rest call to a webservice. In its body it contains a Json file with 18 pairs key, value.
I which to make separate operations on each element so i would like to:
get the different key elements. so i would have an array of the key elements.
With each of those elements, get the corresponding value by dot walking.
Here is what I have:
var obj = JSON.parse(request.body.dataString);
var myKeys = Object.keys(obj)
for (var i = 0; i < myKeys.length; i++){
var iter = myKeys[i];
gs.log(obj.iter);
}
But the gs.log returns undefined.
I have tried to make this:
gs.log(obj.myId);
and it returns the value i want, since myId is one of the elements in keys.
How can i use the elements of my keys array to get the corresponding values?
I have confirmed that hte var myKeys has all the elements of keys and the var obj contains all the json file.
You need to use the [] syntax.
var iter = myKeys[i];
gs.log(obj[iter]);
Plain obj.iter tries to get a property called literally iter. If you want to get a property based on the string value of the variable iter, you need to access the object using obj[iter].

Deleting an entire object in Javascript [duplicate]

This question already has answers here:
Why doesn’t deleting from a Javascript array change its length?
(6 answers)
Closed 8 years ago.
arr = [
{
id:1
},
{
id:2
}
]
This is an example object structure. I want to delete first object in this array.
delete arr[0];
Resulting structure is
[
{
undefined * 1
},
{
id:2
}
]
I have searched a lot and found that deleting an entire object will lead to dangling pointer problems. But i want resulting array to have only one object after deletion. Is there any other way to achieve this?
EDIT
How to do if the object is neither first nor last?
You need to create a shorter array instead. To remove the first element, just slice the array:
arr = arr.slice(1);
When the previous array is discarded the first element will also be discarded.
You could, as an alternative to Array.prototype.slice(), use array.prototype.shift(), which simply removes the first element of the array:
arr = [
{
id:1
},
{
id:2
}
];
console.log(arr); // [Object, Object]
arr.shift();
console.log(arr); // [Object]
References:
Array.prototype.shift().
Array.prototype.splice().
The only way to delete anything from an array is to resize it
arr = arr.slice(1)

How to sort a bi-dimensional javascript array? [duplicate]

This question already has answers here:
Sort an array based on another array of integers
(7 answers)
Closed 8 years ago.
var global=[];
var value=[50,1,4,29];
var title=["d","b","c","a"];
title.forEach(function(title,i) {
global[title]=value[i];
})
I would like to sort the global array by value but I can't figure out how.
I precise I can't use any library jquery,underscore...
thanks !
the goal is to know what object has the less value.
a,b,c,d have values 50,1,4,29
I can sort values but how to know what's the name associated to this value ?
You're not using global[] correctly as an array in your loop. You can't reference array items with [title], you can either push to the array global.push(value[i]) or use global[i] = value[i]. If you use either of these methods you can just call 'global.sort()' to sort the array which will give you [1, 29, 4, 50]. If you want to use the array as multidimensional, you need to change your loop to something like this:
title.forEach(function(title,i) {
global[i] = {};
global[i][title]=value[i];
})
which will give you [Object { d=50}, Object { b=1}, Object { c=4}, Object { a=29}]
If you want to sort this you could use sort which takes a function in which you can write your custom sorter but I don't think you can use this as all your keys are different. If all your keys were the same, say 'value' ,i.e [Object { value=50}, Object { value=1}, Object { value=4}, Object { value=29}] , you could do:
global.sort(function(a,b) {
return parseInt(a.value, 10) - parseInt(b.value, 10);
});
but this can't be applied to your array since all the keys are different.

Categories

Resources