Znajdź obiekt według id w tablicy obiektów JavaScript
Mam tablicę:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
Nie mogę zmienić struktury tablicy. Otrzymuję identyfikator 45
i chcę uzyskać 'bar'
dla tego obiektu w tablicy.
Jak to zrobić w JavaScript lub za pomocą jQuery?
29 answers
Użyj metody find()
:
myArray.find(x => x.id === '45').foo;
From MDN :
Metoda
find()
Zwraca wartość w tablicy, jeśli element w tablicy spełnia podaną funkcję testową. W przeciwnym razie zwracane jestundefined
.
Jeśli chcesz znaleźć jego indeks zamiast tego użyj findIndex()
:
myArray.findIndex(x => x.id === '45');
From MDN :
Metoda
findIndex()
zwraca indeks pierwszego elementu tablicy, który spełnia podane testy funkcja. W przeciwnym razie zwracane jest -1.
Jeśli chcesz uzyskać tablicę pasujących elementów, użyj filter()
metoda zamiast:
myArray.filter(x => x.id === '45');
Zwróci tablicę obiektów. Jeśli chcesz uzyskać tablicę foo
właściwości, możesz to zrobić za pomocą map()
"metoda": {]}
myArray.filter(x => x.id === '45').map(x => x.foo);
Uwaga: metody takie jak find()
lub filter()
i funkcje strzałek nie są obsługiwane przez starsze przeglądarki (np. przeglądarki, należy transpilować swój kod za pomocą Babel (z polyfill).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-01 10:09:54
Ponieważ używasz już jQuery, możesz użyć funkcji grep , która jest przeznaczona do przeszukiwania tablicy:
var result = $.grep(myArray, function(e){ return e.id == id; });
Wynikiem jest tablica z znalezionymi elementami. Jeśli wiesz, że obiekt jest zawsze i występuje tylko raz, możesz po prostu użyć result[0].foo
, aby uzyskać wartość. W przeciwnym razie należy sprawdzić długość tablicy wynikowej. Przykład:
if (result.length == 0) {
// not found
} else if (result.length == 1) {
// access the foo property using result[0].foo
} else {
// multiple items found
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-15 22:26:01
Innym rozwiązaniem jest utworzenie obiektu lookup:
var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
lookup[array[i].id] = array[i];
}
... now you can use lookup[id]...
Jest to szczególnie interesujące, jeśli potrzebujesz wykonać wiele poszukiwań.
Nie będzie to wymagało dużo więcej pamięci, ponieważ identyfikatory i obiekty będą współdzielone.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-09 15:50:09
ECMAScript 2015 zapewnia Znajdź() metoda na tablicach:
var myArray = [
{id:1, name:"bob"},
{id:2, name:"dan"},
{id:3, name:"barb"},
]
// grab the Array item which matchs the id "2"
var item = myArray.find(item => item.id === 2);
// print
console.log(item.name);
Działa bez zewnętrznych bibliotek. Ale jeśli chcesz starsze wsparcie przeglądarki możesz chcieć dołączyć ten polyfill.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-10 15:10:35
Podkreślam.js ma na to ładną metodę:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]
obj = _.find(myArray, function(obj) { return obj.id == '45' })
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-22 12:52:21
Myślę, że najprostszym sposobem byłoby następujące, ale to nie będzie działać na Internet Explorer 8 (lub wcześniej):
var result = myArray.filter(function(v) {
return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-01 16:16:09
Spróbuj wykonać następujące czynności
function findById(source, id) {
for (var i = 0; i < source.length; i++) {
if (source[i].id === id) {
return source[i];
}
}
throw "Couldn't find object with id: " + id;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-09 15:45:04
myArray.filter(function(a){ return a.id == some_id_you_want })[0]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-16 17:31:49
Ogólna i bardziej elastyczna wersja powyższej funkcji findById:
// array = [{key:value},{key:value}]
function objectFindByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
return array[i];
}
}
return null;
}
var array = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var result_obj = objectFindByKey(array, 'id', '45');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-13 20:34:26
Możesz używać filtrów,
function getById(id, myArray) {
return myArray.filter(function(obj) {
if(obj.id == id) {
return obj
}
})[0]
}
get_my_obj = getById(73, myArray);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-13 09:43:20
Możesz to łatwo uzyskać za pomocą map () funkcji:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var found = $.map(myArray, function(val) {
return val.id == 45 ? val.foo : null;
});
//found[0] == "bar";
Przykład roboczy: http://jsfiddle.net/hunter/Pxaua/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-01 15:30:19
Używanie natywnego Array.reduce
var array = [ {'id':'73' ,'foo':'bar'} , {'id':'45' ,'foo':'bar'} , ];
var id = 73;
var found = array.reduce(function(a, b){
return (a.id==id && a) || (b.id == id && b)
});
Zwraca element obiektu, jeśli zostanie znaleziony, w przeciwnym razie false
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-01 21:45:03
Chociaż istnieje wiele poprawnych odpowiedzi, wiele z nich nie odnosi się do faktu, że jest to niepotrzebnie kosztowna operacja, jeśli zostanie wykonana więcej niż raz. W skrajnym przypadku może to być przyczyną rzeczywistych problemów z wydajnością.
W realnym świecie, jeśli przetwarzasz wiele przedmiotów i wydajność jest problemem, znacznie szybciej jest wstępnie zbudować odnośnik:
var items = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var lookup = items.reduce((o,i)=>o[i.id]=o,{});
Możesz następnie uzyskać przedmioty w ustalonym czasie w następujący sposób:
var bar = o[id];
Możesz również rozważyć użycie Mapa zamiast obiektu jako odnośnik: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-23 10:24:18
Możesz wypróbować Sugarjs z http://sugarjs.com/.
Ma bardzo słodką metodę na tablicach, .find
. Więc możesz znaleźć taki element:
array.find( {id: 75} );
Możesz również przekazać obiekt o większej liczbie właściwości, aby dodać kolejną klauzulę "where-clause".
zauważ, że Sugarjs rozszerza rodzime obiekty, a niektórzy ludzie uważają to za bardzo złe...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-01 15:32:12
Na podstawie zaakceptowanej odpowiedzi:
JQuery:
var foo = $.grep(myArray, function(e){ return e.id === foo_id})
myArray.pop(foo)
Lub CoffeeScript:
foo = $.grep myArray, (e) -> e.id == foo_id
myArray.pop foo
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-01 15:54:11
Oto jak zrobiłbym to w czystym JavaScript, w najbardziej minimalny sposób, jaki mogę myśleć, że działa w ECMAScript 3 lub później. Powraca, gdy tylko dopasowanie zostanie znalezione.
var getKeyValueById = function(array, key, id) {
var testArray = array.slice(), test;
while(test = testArray.pop()) {
if (test.id === id) {
return test[key];
}
}
// return undefined if no matching id is found in array
return;
}
var myArray = [{'id':'73', 'foo':'bar'}, {'id':'45', 'foo':'bar'}]
var result = getKeyValueById(myArray, 'foo', '45');
// result is 'bar', obtained from object with id of '45'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-18 10:55:52
Jeśli zrobisz to wiele razy, możesz ustawić mapę (ES6):
const map = new Map( myArray.map(el => [el.id, el]) );
Wtedy możesz po prostu zrobić:
map.get(27).foo
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-20 08:33:08
Możesz to zrobić nawet w czystym JavaScript, używając wbudowanej funkcji "filter"dla tablic:
Array.prototype.filterObjects = function(key, value) {
return this.filter(function(x) { return x[key] === value; })
}
Więc teraz po prostu podaj "id" zamiast key
i " 45 " zamiast value
, a otrzymasz pełny obiekt pasujący do id 45. Czyli,
myArr.filterObjects("id", "45");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-27 05:33:37
Naprawdę podobała mi się Odpowiedź udzielona przez Aarona Digullę, ale musiałem zachować tablicę obiektów, abym mógł ją później powtórzyć. Więc zmodyfikowałem go na
var indexer = {};
for (var i = 0; i < array.length; i++) {
indexer[array[i].id] = parseInt(i);
}
//Then you can access object properties in your array using
array[indexer[id]].property
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-19 03:55:57
Iteracja nad dowolnym elementem w tablicy. Dla każdego przedmiotu, który odwiedzasz, sprawdź jego id. Jeśli pasują, zwróć je.
If you just want Teh codez:
function getId(array, id) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i].id === id) {
return array[i];
}
}
return null; // Nothing found
}
I to samo przy użyciu metod tablicy ECMAScript 5:
function getId(array, id) {
var obj = array.filter(function (val) {
return val.id === id;
});
// Filter returns an array, and we just want the matching item.
return obj[0];
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-01 15:29:51
Dopóki przeglądarka obsługuje ECMA-262 , wydanie 5 (Grudzień 2009), powinno działać, prawie jednolinijkowo:
var bFound = myArray.some(function (obj) {
return obj.id === 45;
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-01 15:51:32
Użyj funkcji Array.prototype.filter()
.
DEMO: https://jsfiddle.net/sumitridhal/r0cz0w5o/4/
JSON
var jsonObj =[
{
"name": "Me",
"info": {
"age": "15",
"favColor": "Green",
"pets": true
}
},
{
"name": "Alex",
"info": {
"age": "16",
"favColor": "orange",
"pets": false
}
},
{
"name": "Kyle",
"info": {
"age": "15",
"favColor": "Blue",
"pets": false
}
}
];
Filtr
var getPerson = function(name){
return jsonObj.filter(function(obj) {
return obj.name === name;
});
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-17 18:05:33
Użycie:
var retObj ={};
$.each(ArrayOfObjects, function (index, obj) {
if (obj.id === '5') { // id.toString() if it is int
retObj = obj;
return false;
}
});
return retObj;
Powinien zwracać obiekt według id.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-01 15:32:55
To rozwiązanie może być pomocne również:
Array.prototype.grep = function (key, value) {
var that = this, ret = [];
this.forEach(function (elem, index) {
if (elem[key] === value) {
ret.push(that[index]);
}
});
return ret.length < 2 ? ret[0] : ret;
};
var bar = myArray.grep("id","45");
Zrobiłem tak jak $.grep
i jeśli jeden obiekt zostanie znaleziony, Funkcja zwróci obiekt, a nie tablicę.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-01 15:53:40
Zaczynając od odpowiedzi aggatona , jest to funkcja, która faktycznie zwraca pożądany element (lub null
jeśli nie została znaleziona), biorąc pod uwagę array
i callback
funkcję, która zwraca prawdziwą wartość dla" poprawnego " elementu:
function findElement(array, callback) {
var elem;
return array.some(function(e) {
if (callback(e)) {
elem = e;
return true;
}
}) ? elem : null;
});
Pamiętaj tylko, że to natywnie nie działa na IE8 -, ponieważ nie obsługuje some
. Może być dostarczony polyfill, alternatywnie zawsze istnieje klasyczna pętla for
:
function findElement(array, callback) {
for (var i = 0; i < array.length; i++)
if (callback(array[i])) return array[i];
return null;
});
Jest szybszy i bardziej kompaktowy. Ale jeśli nie chcesz na nowo odkrywam koło, proponuję użyć biblioteki narzędziowej, takiej jak underscore lub lodash.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:39
Najkrótsza,
var theAnswerObj = _.findWhere(array, {id : 42});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-03 03:52:31
Rozważmy "axesOptions" jako tablicę obiektów o formacie obiektu {: field_type = > 2,: fields = > [1,3,4]}
function getFieldOptions(axesOptions,choice){
var fields=[]
axesOptions.each(function(item){
if(item.field_type == choice)
fields= hashToArray(item.fields)
});
return fields;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-04 06:06:06
Możemy używać metod Jquery $.each ()/$.grep()
var data= [];
$.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}
Lub
var data = $.grep(array, function( n, i ) {
return ( n !== 5 && i > 4 );
});
Użyj składni ES6:
Array.find, Array.filter, Array.forEach, Array.map
Lub użyj Lodash https://lodash.com/docs/4.17.10#filter , podkreślenie https://underscorejs.org/#filter
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-25 06:49:04
Użyj metody filtrowania jQuery:
$(myArray).filter(function()
{
return this.id == desiredId;
}).first();
Zwróci pierwszy element o podanym Id.
Ma również zalety ładnego formatu wyglądającego na C # LINQ.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-09 15:47:27