Does array include object with specific key? [duplicate] - javascript

This question already has answers here:
Check if array of objects contain certain key
(6 answers)
Closed 5 months ago.
I need to find out if an array of a JS object includes an object with a specific key.
I am using,
my_array.filter((e) => Object.keys(e).includes(my_key)).length > 0
but there must be a way to do it simpler.
Any suggestions in addition to Check if array of objects contain certain key ?

Instead of .filter(…).length > 0, use .some(…).
Instead of Object.keys(…).includes(…), use … in … (or Object.hasOwn(…, …) if you need to ignore inherited properties).
So
my_array.some(e => my_key in e)

instead of filter use some, already returns true or false and it shortcircuits as soon as it finds the first
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Related

I can't iterate over a javascript array [duplicate]

This question already has answers here:
How can JavaScript arrays have non-numeric keys?
(2 answers)
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 4 months ago.
I am going crazy here, I have an associative array as seen below which is defined after the page finishes loading. However Array.forEach is returning undefined and I have no idea why. The array is most definitely populated during the loop. Can anyone give me any ideas? Also doesn't work with JQuery's $.each
Arrays are usually a mapping of index (integer from 0 to 232 − 2, inclusive) to value. In your case you've treated the array as a dictionary e.g. key (string) to value.
You've probably done something like this:
members = new Array();
members['animerox1213'] = 'Ashima';
JavaScript allows this, after all it is still an object:
typeof members === 'object'
But instead of adding a value to the array, you've actually set a non-numeric property on the object called animerox1213. That is not how an array should be used and we can observe this by checking the size:
members.length === 0;
Consequently, forEach does not do anything as it considers it an empty array.
That said, it is enumerable with for…in as it's still just an object (with enumerable properties):
for (m in members) {
console.log(m, members[m]);
}
Consider using just an object e.g. members = {} or Map. Note especially the section Objects vs. Maps.

Empty array is shown as object [duplicate]

This question already has answers here:
How can I check if an object is an array? [duplicate]
(51 answers)
Closed 1 year ago.
I wrote a utility function for my nextjs project. In there, I got something that I unexpected. I initialised an empty array which be filled with the data later. When I type check that empty array, it shows an object. I don't want an object. I want an array. Why? Could someone told me why does it happen.
strong text
Yes typeof array is an object in javascript
if you want to check one variable is an object or array then you can use
Array.isArray()
console.log(Array.isArray(arr)) // true
console.log(Array.isArray(obj)) // false

"in" keyword not working properly when used with object.value in node [duplicate]

This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
What is the difference between "in operator" and "includes()" for JavaScript arrays
(4 answers)
Closed 1 year ago.
I need to execute some code. But my code is not working properly. I have made an simple example to demonstrate the malfunction.
When I run
console.log("val" in Object.values({key:"val"})); //returns false
It gives me false. But if I run
console.log(Object.values({key:"val"}))
outputs => ['val']
I don't understand if it is supposed to work like this. If yes. Why ?
Thanks in Advance.....:)
MDN says "the in operator returns true if the specified property is in the specified object or its prototype chain.", Object.values returns an array. To check if an item exists in an array, use the Array.includes method.
console.log(
Object.values({key:"val"}).includes("val")
); // Returns true

need reference for documentation on ternary operator using push [duplicate]

This question already has answers here:
When is the comma operator useful?
(15 answers)
Closed 1 year ago.
I have the following:
let currentLocalStorage = [];
currentLocalStorage = (initialLoad) ? JSON.parse(localStorage.getItem('tasks')): (currentLocalStorage.push(taskInput.value),currentLocalStorage)
which works but I would like to get a reference or documentation for the following:
: (currentLocalStorage.push(taskInput.value),currentLocalStorage)
so basically we are pushing on to the array and then defaulting to the array. I was surprised that we can do this and was wondering where one we look for the documentation
This is using the comma operator. Because .push() returns the new length of the array, you want to make sure you don't assign that to currentLocalStorage, so you use the comma operator to have that expression evaluate to currentLocalStorage.
So it effectively becomes currentLocalStorage = currentLocalStorage in that case, except now the array has one more item thanks to .push().

Why does JavaScript allow accessing an object's property using an array of length 1, as if the array was just the single element itself? [duplicate]

This question already has answers here:
Why does JavaScript convert an array of one string to a string, when used as an object key? [duplicate]
(4 answers)
Why can I access object property with an array?
(2 answers)
Closed 2 years ago.
See this example:
> map = { 5: 'five' }
> map[5]
'five' // Makes sense
> arr = [5]
> map[arr]
'five' // Does not make sense
> arr = [5,6,7]
> map[arr]
undefined // I'm cool with that
So when I access an object's property with an array of length 1, it behaves as if I simply input the single element instead of the array. But when the array's length is anything but 1, it will produce the expected behavior.
What is the purpose of this behavior? To me this would simply make things harder for a developer to find a bug in their code.
If an object index is not a string or Symbol, it's converted to a string as if by its toString() method.
array.toString() performs the equivalent array.join(",").
So
map[arr]
is equivalent to
map[arr.join(",")]
If the array has one element, joining it simply returns that one element converted to a string, so it's equivalent to
map[arr[0].toString()]
and that explains your first result.
But in your second example, it returns the string "5,6,7" and there's no property with that name in the object.

Categories