3항 연산자(?)와 함께 map() 개념을 사용합니다. 다음은 객체 배열입니다 -
let firstCustomerDetails =
[
{firstName: 'John', amount: 100},
{firstName: 'David', amount: 50},
{firstName: 'Bob', amount: 80}
];
let secondCustomerDetails =
[
{firstName: 'John', amount: 400},
{firstName: 'David', amount: 70},
{firstName: 'Bob', amount: 40}
]; 예를 들어, amount 속성으로 객체 배열을 필터링해야 한다고 가정해 보겠습니다. 가장 많은 금액이 고려됩니다.
예시
let firstCustomerDetails =
[
{firstName: 'John', amount: 100},
{firstName: 'David', amount: 50},
{firstName: 'Bob', amount: 80}
];
let secondCustomerDetails =
[
{firstName: 'John', amount: 400},
{firstName: 'David', amount: 70},
{firstName: 'Bob', amount: 40}
];
var output = firstCustomerDetails.map((key, position) =>
key.amount > secondCustomerDetails[position].amount ? key :
secondCustomerDetails[position]
);
console.log(output); 위의 프로그램을 실행하려면 다음 명령을 사용해야 합니다 -
node fileName.js.
여기에서 내 파일 이름은 demo83.js입니다.
출력
이것은 다음과 같은 출력을 생성합니다 -
PS C:\Users\Amit\JavaScript-code> node demo83.js
[
{ firstName: 'John', amount: 400 },
{ firstName: 'David', amount: 70 },
{ firstName: 'Bob', amount: 80 }
]