[英]Return values from array of objects
我有以下結構
const objArray = [ { shiftId: 89192 },
{ shiftId: 89193 },
{ shiftId: 89190 } ]
對象數組。 我正在嘗試映射並提取shiftId
的值
我所做的是object.map(el=> Object.values(el));
但此映射返回以下結構,因為Object.values
不幸返回一個數組。
[ [ 89192 ], [ 89193 ], [ 89190 ] ]
只有一個元素的嵌套數組。 我怎樣才能映射到這個只支持一個數組。
如果要提取shiftId
屬性,只需指定要提取該特定屬性,而不是使用Object.values
:
const shiftIds = object.map(({ shiftId }) => shiftId);
請注意,您在那里有一個數組- 如果您調用變量arrOfShiftObjs
或類似的東西,而不是調用它object
,您的代碼會更容易理解。
要從每個項目中提取多個值並將它們放入一個更大的數組中,請使用flatMap
:
const arr = [{ shiftId: 89192, id: 'id' }, { shiftId: 89193, id: 'id' }, { shiftId: 89190, id: 'id' } ]; const values = arr.flatMap(Object.values); console.log(values);
或者,如果對象還包含您不想包含的其他屬性,並且您只需要shiftId
和id
:
const arr = [{ shiftId: 89192, id: 'id' }, { shiftId: 89193, id: 'id' }, { shiftId: 89190, id: 'id' } ]; const values = arr.flatMap(({ shiftId, id }) => [shiftId, id]); console.log(values);
就像使用所有較新的功能一樣,如果您想支持還沒有它的瀏覽器,請使用 polyfill。 當然,你也可以reduce
const arr = [{ shiftId: 89192, id: 'id' }, { shiftId: 89193, id: 'id' }, { shiftId: 89190, id: 'id' } ]; const values = arr.reduce((a, { shiftId, id }) => { a.push(shiftId, id); return a; }, []); console.log(values);
您可以從第一個找到的值中獲取該屬性。
var array = [{ anonymous: { shiftId: 89192 } }, { anonymous: { shiftId: 89193 } }, { anonymous: { shiftId: 89190 } }], values = array.map(o => Object.values(o)[0].shiftId); console.log(values);
使用對象解構和Array.prototype.map
let array = [{ anonymous: { shiftId: 89192 } }, { anonymous: { shiftId: 89193 } }, { anonymous: { shiftId: 89190 } }] let out = array.map(({anonymous: {shiftId}}) => shiftId) console.log(out)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.