Find object by id in an array of JavaScript objects
Use the find()
method:
myArray.find(x => x.id === '45').foo;
From MDN:
The
find()
method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwiseundefined
is returned.
If you want to find its index instead, use findIndex()
:
myArray.findIndex(x => x.id === '45');
From MDN:
The
findIndex()
method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
If you want to get an array of matching elements, use the filter()
method instead:
myArray.filter(x => x.id === '45');
This will return an array of objects. If you want to get an array of foo
properties, you can do this with the map()
method:
myArray.filter(x => x.id === '45').map(x => x.foo);
Side note: methods like find()
or filter()
, and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).
From an array of objects, extract value of a property as array
Here is a shorter way of achieving it:
let result = objArray.map(a => a.foo);
OR
let result = objArray.map(({ foo }) => foo)
You can also check Array.prototype.map()
.
Select a property from an array of objects based on a value : Javascript
You can use reduce
and check if the checked
property is true, then push
(As pointed out by assoron) the value to the accumulator - there is no need for 2 loops:
const arr = [
{ "value": "abc", "checked": true },
{ "value": "xyz", "checked": false },
{ "value": "lmn", "checked": true }
]
const filtered = arr.reduce((a, o) => (o.checked && a.push(o.value), a), [])
console.log(filtered)
Find a value in an array of objects in Javascript
You can loop over the array and test for that property:
function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
var resultObject = search("string 1", array);
How to check if property of an objects of array matches with one of the values in another array of object
First off, you'll have to make sure if the ID types are correct. Users has Number type for IDs but attendingUsers has String type.
Let's say they're both the same type for the code below (I'm going with string).
You can turn the attendingUsers array into an array of strings with:
const attendingUsersIds = attendingUsers.map(attendingUser => attendingUser.id)
Then match the ids with:
const matchedUsers = users.filter(user => attendingUsersIds.includes(user.id))
If they're intended to not be the same type, you can use user.id.toString()
to turn the Number into a String or parseInt(attendingUser.id)
to turn the String into a Number.
Accessing Object Property Values Within an Array - JavaScript
You can acces items in arrays at given position by their index. In javascript indexes of arrays are starting with 0: myArray[0]
. To access the property of the returned object just use dot-notation: myArray[0].myProperty
.
let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];
console.log(object1[1].job);
Sort array of objects by string property value
It's easy enough to write your own comparison function:
function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}
objs.sort( compare );
Or inline (c/o Marco Demaio):
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))
Or simplified for numeric (c/o Andre Figueiredo):
objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort
Object of array of objects. Get the length of all values with the same property
A straight-forward approach:
let obj = {
"array1": [
{"label": "something1", "ref": "option2a"},
{"label": "something2", "ref": "option2b"},
{"label": "something3", "ref": "option2a"},
{"label": "something4", "ref": "option2a"},
{"label": "something5", "ref": "option2a"}
],
"array2": [
{"label": "something6 is the longest label", "ref": "option3a"},
{"label": "Other", "ref": "option3b"}
]
};
let longest = 0
for (key in obj){
if (!obj.hasOwnProperty(key)) continue;
for (let x of obj[key]){
if (x.label.length > longest)
longest = x.label.length;
}
}
console.log(longest);
Related Topics
How to Group an Array of Objects by Key
How to Format Numbers as Currency Strings
Uncaught Referenceerror: $ Is Not Defined
Onclick or Inline Script Isn't Working in Extension
One-Liner to Take Some Properties from Object in Es 6
Wait Until All Promises Complete Even If Some Rejected
JavaScript Equivalent of Python'S Zip Function
Difference Between a Function Expression VS Declaration in JavaScript
JavaScript: Natural Sort of Alphanumerical Strings
Async/Await Implicitly Returns Promise
Load and Execute Order of Scripts
Escaping HTML Strings With Jquery
Detecting an "Invalid Date" Date Instance in JavaScript
How to Get Started With Node.Js
How to Distinguish Between Left and Right Mouse Click With Jquery