For example, I have:
var Data = [
{ id_list: 1, name: 'Nick', token: '312312' },
{ id_list: 2, name: 'John', token: '123123' },
]
Then, I want to sort/reverse this object by name
, for example. And then I want to get something like this:
var Data = [
{ id_list: 2, name: 'John', token: '123123' },
{ id_list: 1, name: 'Nick', token: '312312' },
]
And now I want to know the index of the object with property name='John'
to get the value of the property token.
How do I solve the problem?
asked Aug 24, 2011 at 14:13
5
Since the sort part is already answered. I'm just going to propose another elegant way to get the indexOf of a property in your array
Your example is:
var Data = [
{id_list:1, name:'Nick', token:'312312'},
{id_list:2, name:'John', token:'123123'}
]
You can do:
var index = Data.map[function[e] { return e.name; }].indexOf['Nick'];
Array.prototype.map
is not available on Internet Explorer 7 or Internet Explorer 8.
ES5 Compatibility
And here it is with ES6 and arrow syntax, which is even simpler:
const index = Data.map[e => e.name].indexOf['Nick'];
xxx
1,1331 gold badge11 silver badges22 bronze badges
answered Apr 4, 2014 at 13:54
German AttanasioGerman Attanasio
20.4k7 gold badges47 silver badges63 bronze badges
11
If you're fine with using ES6, arrays now have the findIndex function. Which means you can do something like this:
const index = Data.findIndex[item => item.name === 'John'];
answered Sep 16, 2016 at 10:19
silverlight513silverlight513
4,8123 gold badges25 silver badges36 bronze badges
5
As the other answers suggest, looping through the array is probably the best way. But I would put it in its own function, and make it a little more abstract:
function findWithAttr[array, attr, value] {
for[var i = 0; i < array.length; i += 1] {
if[array[i][attr] === value] {
return i;
}
}
return -1;
}
var Data = [
{id_list: 2, name: 'John', token: '123123'},
{id_list: 1, name: 'Nick', token: '312312'}
];
With this, not only can you find which one contains 'John', but you can find which contains the token '312312':
findWithAttr[Data, 'name', 'John']; // returns 0
findWithAttr[Data, 'token', '312312']; // returns 1
findWithAttr[Data, 'id_list', '10']; // returns -1
The function returns -1 when not found, so it follows the same construct as Array.prototype.indexOf[].
answered Aug 24, 2011 at 15:45
Chris PickettChris Pickett
2,8121 gold badge13 silver badges7 bronze badges
3
If you're having issues with Internet Explorer, you could use the map[] function which is supported from 9.0 onward:
var index = Data.map[item => item.name].indexOf["Nick"];
answered Jan 3, 2019 at 1:33
Alain T.Alain T.
35.4k4 gold badges31 silver badges48 bronze badges
1
var index = Data.findIndex[item => item.name == "John"]
Which is a simplified version of:
var index = Data.findIndex[function[item]{ return item.name == "John"}]
From mozilla.org:
The findIndex[] method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
answered Mar 19, 2018 at 19:29
edankedank
5896 silver badges16 bronze badges
4
Only way known to me is to loop through all array:
var index = -1;
for[var i=0; i item.value === 'smth'] !== -1
answered Jan 26, 2018 at 16:08
2
You can use Array.sort using a custom function as a parameter to define your sorting mechanism.
In your example, it would give:
var Data = [
{id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]
Data.sort[function[a, b]{
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
}];
alert["First name is : " + Data[0].name]; // alerts 'John'
alert["Second name is : " + Data[1].name]; // alerts 'Nick'
The sort function must return either -1 if a should come before b, 1 if a should come after b and 0 if both are equal. It's up to you to define the right logic in your sorting function to sort the array.
Missed the last part of your question where you want to know the index. You would have to loop through the array to find that as others have said.
answered Aug 24, 2011 at 14:24
This might be useful:
function showProps[obj, objName] {
var result = "";
for [var i in obj]
result += objName + "." + i + " = " + obj[i] + "\n";
return result;
}
I copied this from Working with objects.
answered Feb 4, 2012 at 8:46
AshishAshish
1,17111 silver badges12 bronze badges
Use a small workaround:
Create a new array with names as indexes. After that all searches will use indexes. So, only one loop. After that you don't need to loop through all elements!
var Data = [
{id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]
var searchArr = []
Data.forEach[function[one]{
searchArr[one.name]=one;
}]
console.log[searchArr['Nick']]
//jsbin.com/xibala/1/edit
Live example.
answered Jan 24, 2015 at 9:01
1
I extended Chris Pickett's answer, because in my case I needed to search deeper than one attribute level:
function findWithAttr[array, attr, value] {
if [attr.indexOf['.'] >= 0] {
var split = attr.split['.'];
var attr1 = split[0];
var attr2 = split[1];
for[var i = 0; i < array.length; i += 1] {
if[array[i][attr1][attr2] === value] {
return i;
}
}
} else {
for[var i = 0; i < array.length; i += 1] {
if[array[i][attr] === value] {
return i;
}
}
};
};
You can pass 'attr1.attr2' into the function.
answered Nov 30, 2015 at 17:38
Ed SheeEd Shee
9311 gold badge7 silver badges22 bronze badges
Use this:
Data.indexOf[_.find[Data, function[element] {
return element.name === 'John';
}]];
It is assuming you are using Lodash or Underscore.js.
answered Jan 18, 2017 at 11:46
ElloneEllone
3,50211 gold badges37 silver badges67 bronze badges
var fields = {
teste:
{
Acess:
{
Edit: true,
View: false
}
},
teste1:
{
Acess:
{
Edit: false,
View: false
}
}
};
console.log[find[fields,'teste']];
function find[fields,field] {
for[key in fields] {
if[key == field] {
return true;
}
}
return false;
}
If you have one Object with multiple objects inside, if you want know if some object are include on Master object, just use find[MasterObject, 'Object to Search']
. This function will return the response if it exists or not [TRUE or FALSE].
I hope to help with this - can see the example on JSFiddle.
answered Jul 18, 2017 at 14:40
2
If you want to get the value of the property token then you can also try this:
let data=[
{ id_list: 1, name: 'Nick', token: '312312' },
{ id_list: 2, name: 'John', token: '123123' },
]
let resultingToken = data[_.findKey[data,['name','John']]].token
where _.findKey is a Lodash function.
answered Nov 14, 2019 at 12:00
Akash SinghAkash Singh
5374 silver badges7 bronze badges
You can use findIndex in Lodash library.
Example:
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.findIndex[users, function[o] { return o.user == 'barney'; }];
// => 0
// The `_.matches` iteratee shorthand.
_.findIndex[users, { 'user': 'fred', 'active': false }];
// => 1
// The `_.matchesProperty` iteratee shorthand.
_.findIndex[users, ['active', false]];
// => 0
// The `_.property` iteratee shorthand.
_.findIndex[users, 'active'];
// => 2
answered Aug 29, 2021 at 12:22
Iman MarashiIman Marashi
5,34736 silver badges50 bronze badges
Alternatively to German Attanasio Ruiz's answer, you can eliminate the second loop by using Array.reduce[] instead of Array.map[];
var Data = [
{ name: 'hypno7oad' }
]
var indexOfTarget = Data.reduce[function [indexOfTarget, element, currentIndex] {
return [element.name === 'hypno7oad'] ? currentIndex : indexOfTarget;
}, -1];
answered Nov 4, 2014 at 20:45
hypno7oadhypno7oad
1,4311 gold badge19 silver badges28 bronze badges
Maybe the Object.keys, Object.entries, and Object.values methods might help.
answered Apr 5 at 1:44
milahmilah
11 bronze badge
1
Using Underscore.js:
var index = _.indexOf[_.pluck[item , 'name'], 'Nick'];
answered Mar 10, 2020 at 6:04
M Faisal HameedM Faisal Hameed
6531 gold badge6 silver badges22 bronze badges