lodash를 사용하여 Array에서 객체를 찾아 반환하는 방법은 무엇입니까?
내 사물 :
[
{
description: 'object1', id: 1
},
{
description: 'object2', id: 2
}
{
description: 'object3', id: 3
}
{
description: 'object4', id: 4
}
]
아래 함수에서 일치하는 ID를 찾기 위해 설명을 전달합니다.
function pluckSavedView(action, view) {
console.log('action: ', action);
console.log('pluckSavedView: ', view); // view = 'object1'
var savedViews = retrieveSavedViews();
console.log('savedViews: ', savedViews);
if (action === 'delete') {
var delete_id = _.result(_.find(savedViews, function(description) {
return description === view;
}), 'id');
console.log('delete_id: ', delete_id); // should be '1', but is undefined
}
}
lodash의 find 메소드를 사용하려고합니다 : https://lodash.com/docs#find
그러나 내 변수 delete_id가 정의되지 않았습니다.
이 질문을 확인하는 사람들을 위해 업데이트 한 Ramda는 lodash와 동일한 기능을 수행하지만 더 기능적인 프로그래밍 방식으로 수행하는 훌륭한 라이브러리입니다. : http://ramdajs.com/0.21.0/docs/
콜백에 전달 된 인수는 배열의 요소 중 하나입니다. 배열의 요소는 형식의 객체입니다 {description: ..., id: ...}.
var delete_id = _.result(_.find(savedViews, function(obj) {
return obj.description === view;
}), 'id');
당신이 링크 한 문서 (lodash v3)의 또 다른 대안 :
_.find(savedViews, 'description', view);
Lodash v4 :
_.find(savedViews, ['description', view]);
lodash와 ES5
var song = _.find(songs, {id:id});
lodash와 ES6
let song = _.find(songs, {id});
https://lodash.com/docs#find의 문서
바닐라 JS에서이 작업을 쉽게 수행 할 수 있습니다.
사용 find
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];
const view = 'object2';
const delete_id = savedViews.find(obj => {
return obj.description === view;
}).id;
console.log(delete_id);
사용 filter(원래 답변)
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];
const view = 'object2';
const delete_id = savedViews.filter(function (el) {
return el.description === view;
})[0].id;
console.log(delete_id);
이 find메소드를 사용하면 콜백에 다음과 같이 각 요소의 값이 전달됩니다.
{
description: 'object1', id: 1
}
따라서 다음과 같은 코드가 필요합니다.
_.find(savedViews, function(o) {
return o.description === view;
})
var delete_id = _(savedViews).where({ description : view }).get('0.id')
Lodash 또는 Ramda 또는 기타 추가 종속성이 필요하지 않습니다.
기능적인 방식으로 ES6 find () 함수를 사용하십시오.
savedViews.find(el => el.description === view)
때때로 당신은 그들과 함께 제공되는 모든 장점을 얻기 위해 타사 라이브러리를 사용해야합니다. 그러나 일반적으로 필요하지 않은 종속성은 피하십시오 . 종속성은 다음과 같습니다.
- 번들 코드 크기를 늘리고
- 최신 정보를 유지해야합니다.
- 버그 나 보안 위험이 발생할 수 있습니다
이를 위해 _.find의 기본 사용법 예제 인 Array에서 지정된 Object를 찾습니다.
const array =
[
{
description: 'object1', id: 1
},
{
description: 'object2', id: 2
},
{
description: 'object3', id: 3
},
{
description: 'object4', id: 4
}
];
이것은 잘 작동합니다
q = _.find(array, {id:'4'}); // delete id
console.log(q); // {description: 'object4', id: 4}
_.find will help with returning an element in an array, rather than it’s index. So if you have an array of objects and you want to find a single object in the array by a certain key value pare _.find is the right tools for the job.
You can use the following
import { find } from 'lodash'
Then to return the entire object (not only its key or value) from the list with the following:
let match = find(savedViews, { 'ID': 'id to match'});
Import lodash using
$ npm i --save lodash
var _ = require('lodash');
var objArrayList =
[
{ name: "user1"},
{ name: "user2"},
{ name: "user2"}
];
var Obj = _.find(objArrayList, { name: "user2" });
// Obj ==> { name: "user2"}
Fetch id basing on name
{
"roles": [
{
"id": 1,
"name": "admin",
},
{
"id": 3,
"name": "manager",
}
]
}
fetchIdBasingOnRole() {
const self = this;
if (this.employee.roles) {
var roleid = _.result(
_.find(this.getRoles, function(obj) {
return obj.name === self.employee.roles;
}),
"id"
);
}
return roleid;
},
'Programing' 카테고리의 다른 글
| 하나 이상의 공백 또는 탭으로 문자열 분해 (0) | 2020.06.29 |
|---|---|
| EF Core를 사용하여 ASP.NET Core에서 마이그레이션을 적용 취소하는 방법 (0) | 2020.06.29 |
| 날짜 범위에서 일을 생성 (0) | 2020.06.29 |
| "sizeof (a? true : false)"가 4 바이트의 출력을 제공하는 이유는 무엇입니까? (0) | 2020.06.29 |
| UIWebView에서 HTML 내용 읽기 (0) | 2020.06.29 |