속성 값으로 객체 배열에서 JavaScript 객체 가져 오기 [duplicate]
이 질문에 이미 답변이 있습니다.
네 개의 객체 배열이 있다고 가정 해 보겠습니다.
var jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
];
예를 들어 루프 없이 {a: 5, b: 6}
속성 값으로 세 번째 개체 ( )를 가져올 수있는 방법이 있습니까?b
for...in
Filter
속성이 값과 일치하는 객체의 배열은 배열을 반환합니다.
var result = jsObjects.filter(obj => {
return obj.b === 6
})
Array.prototype.filter ()에 대한 MDN 문서를 참조하십시오.
const jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
]
let result = jsObjects.filter(obj => {
return obj.b === 6
})
console.log(result)
Find
배열의 첫 번째 요소 / 객체의 값, 그렇지 않으면 undefined
반환됩니다.
var result = jsObjects.find(obj => {
return obj.b === 6
})
Array.prototype.find () 의 MDN 문서를 참조하십시오.
const jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
]
let result = jsObjects.find(obj => {
return obj.b === 6
})
console.log(result)
jsObjects.find(x => x.b === 6)
MDN에서 :
이
find()
메서드는 배열의 요소가 제공된 테스트 함수를 충족하는 경우 배열의 값을 반환합니다. 그렇지 않으면undefined
반환됩니다.
참고 : find()
및 화살표 함수와 같은 메서드 는 IE와 같은 이전 브라우저에서 지원되지 않으므로 이러한 브라우저를 지원하려면 Babel을 사용하여 코드를 트랜스 파일해야합니다 .
나는 당신이 for 루프에 반대하는 이유를 모르겠습니다 (아마 for 루프를 의미했을 것입니다. 특별히 for..in이 아니라), 그들은 빠르고 읽기 쉽습니다. 어쨌든 여기 몇 가지 옵션이 있습니다.
For 루프 :
function getByValue(arr, value) {
for (var i=0, iLen=arr.length; i<iLen; i++) {
if (arr[i].b == value) return arr[i];
}
}
.필터
function getByValue2(arr, value) {
var result = arr.filter(function(o){return o.b == value;} );
return result? result[0] : null; // or undefined
}
.각각
function getByValue3(arr, value) {
var result = [];
arr.forEach(function(o){if (o.b == value) result.push(o);} );
return result? result[0] : null; // or undefined
}
반면에 실제로 for..in을 의미하고 값이 6 인 속성을 가진 객체를 찾으려면 검사 할 이름을 전달하지 않는 한 for..in을 사용해야합니다. 예 :
function getByValue4(arr, value) {
var o;
for (var i=0, iLen=arr.length; i<iLen; i++) {
o = arr[i];
for (var p in o) {
if (o.hasOwnProperty(p) && o[p] == value) {
return o;
}
}
}
}
시도 배열 필터 필터에 대한 방법 array of objects
과를 property
.
var jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
];
배열 필터 방법 사용 :
var filterObj = jsObjects.filter(function(e) {
return e.b == 6;
});
for in 루프 사용 :
for (var i in jsObjects) {
if (jsObjects[i].b == 6) {
console.log(jsObjects[i]); // {a: 5, b: 6}
}
}
작업 바이올린 : https://jsfiddle.net/uq9n9g77/
underscore.js 사용 :
var foundObject = _.findWhere(jsObjects, {b: 6});
OK, 거기를 할 수있는 몇 가지 방법이 있지만,하자가 단순한 하나이 작업을 수행하는 최신 방식으로 시작,이 함수가 호출됩니다 find()
.
당신이 사용하는 경우 그냥주의 find
는, 그래서 transpiled 할 필요도 IE11 dosn't 지원으로 ...
그래서 당신은 당신이 말한 대로이 객체를 가지고 있습니다.
var jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
];
함수를 작성하고 다음과 같이 얻을 수 있습니다.
function filterValue(obj, key, value) {
return obj.find(function(v){ return v[key] === value});
}
다음과 같은 기능을 사용하십시오.
filterValue(jsObjects, "b", 6); //{a: 5, b: 6}
또한에 ES6 도의 버전을 단축 :
const filterValue = (obj, key, value)=> obj.find(v => v[key] === value);
이 메서드는 일치하는 첫 번째 값만 반환합니다. 더 나은 결과와 브라우저 지원을 위해 다음을 사용할 수 있습니다 filter
.
const filterValue = (obj, key, value)=> obj.filter(v => v[key] === value);
그리고 우리는 돌아올 것입니다 [{a: 5, b: 6}]
...
이 메서드는 대신 배열을 반환합니다.
for 루프도 간단하게 사용하고 다음과 같은 함수를 만듭니다.
function filteredArray(arr, key, value) {
const newArray = [];
for(i=0, l=arr.length; i<l; i++) {
if(arr[i][key] === value) {
newArray.push(arr[i]);
}
}
return newArray;
}
다음과 같이 부릅니다.
filteredArray(jsObjects, "b", 6); //[{a: 5, b: 6}]
ECMAScript 6 제안에는 Array
방법 find()
과 findIndex()
. MDN은 또한 모든 브라우저에서 이러한 기능을 얻기 위해 포함 할 수있는 polyfill을 제공합니다.
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 6, 8, 12].find(isPrime) ); // undefined, not found
console.log( [4, 5, 8, 12].find(isPrime) ); // 5
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 6, 8, 12].findIndex(isPrime) ); // -1, not found
console.log( [4, 6, 7, 12].findIndex(isPrime) ); // 2
올바르게 이해하면 b
속성이 6
? 인 배열에서 객체를 찾고 싶습니다 .
var found;
jsObjects.some(function (obj) {
if (obj.b === 6) {
found = obj;
return true;
}
});
또는 밑줄을 사용하는 경우 :
var found = _.select(jsObjects, function (obj) {
return obj.b === 6;
});
배열이 아닌 단일 결과를 찾고 있다면 축소를 제안 할 수 있습니까?
다음은 일치하는 객체가있는 경우 반환하거나없는 경우 null을 반환하는 일반 'ole javascript의 솔루션입니다.
var result = arr.reduce(function(prev, curr) { return (curr.b === 6) ? curr : prev; }, null);
아래와 같이 화살표 기능과 함께 사용할 수 있습니다.
var demoArray = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
var result = demoArray.filter( obj => obj.name === 'apples')[0];
console.log(result);
// {name: 'apples', quantity: 2}
How about using _.find(collection, [predicate=_.identity], [fromIndex=0])
of lo-dash to get object from array of objects by object property value. You could do something like this:
var o = _.find(jsObjects, {'b': 6});
Arguments:
collection (Array|Object): The collection to inspect.
[predicate=_.identity] (Function): The function invoked per iteration.
[fromIndex=0] (number): The index to search from.
Returns
(*): Returns the matched element (in your case, {a: 5, b: 6}), else undefined.
In terms of performance, _.find()
is faster as it only pulls the first object with property {'b': 6}
, on the other hand, if suppose your array contains multiple objects with matching set of properties (key:value), then you should consider using _.filter()
method. So in your case, as your array has a single object with this property, I would use _.find()
.
See this documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
Example :
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries));
// { name: 'cherries', quantity: 5 }
Just improved the fastest/best part of this answer to be more re-usable/clear:
function getElByPropVal(arr, prop, val){
for (var i = 0, length = arr.length; i < length; i++) {
if (arr[i][prop] == val){
return arr[i];
}
}
}
To get first object from array of objects by a specific property value:
function getObjectFromObjectsArrayByPropertyValue(objectsArray, propertyName, propertyValue) {
return objectsArray.find(function (objectsArrayElement) {
return objectsArrayElement[propertyName] == propertyValue;
});
}
function findObject () {
var arrayOfObjectsString = document.getElementById("arrayOfObjects").value,
arrayOfObjects,
propertyName = document.getElementById("propertyName").value,
propertyValue = document.getElementById("propertyValue").value,
preview = document.getElementById("preview"),
searchingObject;
arrayOfObjects = JSON.parse(arrayOfObjectsString);
console.debug(arrayOfObjects);
if(arrayOfObjects && propertyName && propertyValue) {
searchingObject = getObjectFromObjectsArrayByPropertyValue(arrayOfObjects, propertyName, propertyValue);
if(searchingObject) {
preview.innerHTML = JSON.stringify(searchingObject, false, 2);
} else {
preview.innerHTML = "there is no object with property " + propertyName + " = " + propertyValue + " in your array of objects";
}
}
}
pre {
padding: 5px;
border-radius: 4px;
background: #f3f2f2;
}
textarea, button {
width: 100%
}
<fieldset>
<legend>Input Data:</legend>
<label>Put here your array of objects</label>
<textarea rows="7" id="arrayOfObjects">
[
{"a": 1, "b": 2},
{"a": 3, "b": 4},
{"a": 5, "b": 6},
{"a": 7, "b": 8, "c": 157}
]
</textarea>
<hr>
<label>property name: </label> <input type="text" id="propertyName" value="b"/>
<label>property value: </label> <input type="text" id="propertyValue" value=6 />
</fieldset>
<hr>
<button onclick="findObject()">find object in array!</button>
<hr>
<fieldset>
<legend>Searching Result:</legend>
<pre id="preview">click find</pre>
</fieldset>
Using find with bind to pass specific key values to a callback function.
function byValue(o) {
return o.a === this.a && o.b === this.b;
};
var result = jsObjects.find(byValue.bind({ a: 5, b: 6 }));
var result = jsObjects.filter(x=> x.b === 6);
will be better, using return in filter sometimes you can't get result (I dunno why)
var jsObjects = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}];
to access the third object, use: jsObjects[2];
to access the third object b value, use: jsObjects[2].b;
'Nice programing' 카테고리의 다른 글
원격을 특정 커밋으로 재설정 (0) | 2020.10.02 |
---|---|
한 분기에서 다른 분기로 커밋을 복사하는 방법은 무엇입니까? (0) | 2020.09.30 |
파이썬에서 파일 크기를 확인하는 방법은 무엇입니까? (0) | 2020.09.30 |
문자열의 마지막 문자를 어떻게 얻을 수 있습니까? (0) | 2020.09.30 |
문자열에서 마지막 문자 제거 (0) | 2020.09.30 |