How to access the first property of a Javascript object?
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'
Object.values(obj)[0]; // returns 'someVal'
Using this you can access also other properties by indexes. Be aware tho! Object.keys
or Object.values
return order is not guaranteed as per ECMAScript however unofficially it is by all major browsers implementations, please read https://stackoverflow.com/a/23202095 for details on this.
Getting the first index of an object
If the order of the objects is significant, you should revise your JSON schema to store the objects in an array:
[
{"name":"foo", ...},
{"name":"bar", ...},
{"name":"baz", ...}
]
or maybe:
[
["foo", {}],
["bar", {}],
["baz", {}]
]
As Ben Alpert points out, properties of Javascript objects are unordered, and your code is broken if you expect them to enumerate in the same order that they are specified in the object literal—there is no "first" property.
How can I get the index of an object by its property in JavaScript?
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().
Get the index of the object inside an array, matching a condition
As of 2016, you're supposed to use Array.findIndex
(an ES2015/ES6 standard) for this:
a = [ {prop1:"abc",prop2:"qwe"}, {prop1:"bnmb",prop2:"yutu"}, {prop1:"zxvz",prop2:"qwrq"}]; index = a.findIndex(x => x.prop2 ==="yutu");
console.log(index);
How to find index of an object by key and value in an javascript array
The Functional Approach
All the cool kids are doing functional programming (hello React users) these days so I thought I would give the functional solution. In my view it's actually a lot nicer than the imperatival for
and each
loops that have been proposed thus far and with ES6 syntax it is quite elegant.
Update
There's now a great way of doing this called findIndex
which takes a function that return true
/false
based on whether the array element matches (as always, check for browser compatibility though).
var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
});
With ES6 syntax you get to write this:
var index = peoples.findIndex(p => p.attr1 == "john");
The (Old) Functional Approach
TL;DR
If you're looking for index
where peoples[index].attr1 == "john"
use:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Explanation
Step 1
Use .map()
to get an array of values given a particular key:
var values = object_array.map(function(o) { return o.your_key; });
The line above takes you from here:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
To here:
var values = [ "bob", "john", "larry" ];
Step 2
Now we just use .indexOf()
to find the index of the key we want (which is, of course, also the index of the object we're looking for):
var index = values.indexOf(your_value);
Solution
We combine all of the above:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Or, if you prefer ES6 syntax:
var index = peoples.map((o) => o.attr1).indexOf("john");
Demo:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
console.log("index of 'john': " + index);
var index = peoples.map((o) => o.attr1).indexOf("larry");
console.log("index of 'larry': " + index);
var index = peoples.map(function(o) { return o.attr1; }).indexOf("fred");
console.log("index of 'fred': " + index);
var index = peoples.map((o) => o.attr2).indexOf("pizza");
console.log("index of 'pizza' in 'attr2': " + index);
Get First Index in Array Object Type Scripts
you can try like this
dataList: Array<any> = [];
data: any;
constructor(private apiService: ApiService) {
let labels = [];
this.apiService.getEncounterDashBoard(this.searchCond)
.subscribe(data => {
this.dataList = data.result;
labels = this.dataList[0];
// here you can see that we are access the data inside the subscription block bcs javascript is asynchronous. So it is not wait complete the api call
});
}
In an array of objects, fastest way to find the index of an object whose attributes match a search
Maybe you would like to use higher-order functions such as "map".
Assuming you want search by 'field' attribute:
var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];
How to get the first element of an array?
like this
alert(ary[0])
Related Topics
React - Preventing Form Submission
Why Does Isnan(" ") (String with Spaces) Equal False
Parsing Url Hash/Fragment Identifier with JavaScript
Validate That a String Is a Positive Integer
Multiple Path Names for a Same Component in React Router
Secure Random Numbers in JavaScript
Detecting Line-Breaks with Jquery
Math Random Number Without Repeating a Previous Number
Split String Only on First Instance of Specified Character
Es6: Conditional & Dynamic Import Statements
Sanitizing User Input Before Adding It to the Dom in JavaScript
Element Not Visible Error (Not Able to Click an Element)
Convert Js Date Time to MySQL Datetime
Sort Objects in an Array Alphabetically on One Property of the Array
Jquery .On() Method with Multiple Event Handlers to One Selector
How to Serialize an Object into a List of Url Query Parameters