簡體   English   中英

如何從具有特定鍵值的對象數組中獲取 object?

[英]How to get an object from an array of objects with a specific value for a key?

例如,我們有以下對象數組

[
{ x_id: 3, name: abc, class: 3rd, subject: maths},
{ x_id: 33, name: sad, class: 4th, subject: maths},
{ x_id: 12, name: fds, class: 3rd, subject: phy},
{ x_id: 4, name: atgr, class: 10th, subject: sst},
]

x_id 4 的 Output

{ x_id: 4, name: atgr, class: 10th, subject: sst}

您可以使用 .find() 執行此操作,例如這是您的數組

const array = [
{ x_id: 3, name: 'abc', class: '3rd', subject: 'maths'},
{ x_id: 33, name: 'sad', class: '4th', subject: 'maths'},
{ x_id: 12, name: 'fds', class: '3rd', subject: 'phy'},
{ x_id: 4, name: 'atgr', class: '10th', subject: 'sst'},
];

使用此方法,您將迭代並在數組中找到您要查找的元素

var result = array.find(x => x.x_id === 4);
console.log(result); //returns { x_id: 4, name: 'atgr', class: '10th', subject: 'sst'}

https://jsfiddle.net/kenpy/0uj2eo4f/3/

    var array1 = [
    { x_id: 3, name: "abc", class: "3rd", subject: "maths" },
    { x_id: 33, name: "sad", class: "4th", subject: "maths" },
    { x_id: 12, name: "fds", class: "3rd", subject: "phy" },
    { x_id: 4, name: "atgr", class: "10th", subject: "sst" },
    { x_id: 4, name: "atgr", class: "12th", subject: "phy" }
]
// returns the first element, that satisfies the provided testing function.
let element = array1.find(element => element.x_id === 4);
console.log(element);

// returns the all elements, that satisfies the provided testing function.
let results = array1.filter(element => element.x_id === 4);
console.log(results);

尋找()

使用find()搜索滿足提供的 function ( element => element.x_id === 4 ) 的第一個元素

let element = array1.find(element => element.x_id === 4);
console.log(element);

返回

{ x_id: 4, name: 'atgr', class: '10th', subject: 'sst' }

篩選()

使用filter()搜索滿足提供的 function ( element => element.x_id === 4 ) 的所有對象

let results = array1.filter(element => element.x_id === 4);
console.log(results);

返回

[ 
  { x_id: 4, name: 'atgr', class: '10th', subject: 'sst' },
  { x_id: 4, name: 'atgr', class: '12th', subject: 'phy' } 
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM