[英]Return values from array of objects
I have the following structure我有以下结构
const objArray = [ { shiftId: 89192 },
{ shiftId: 89193 },
{ shiftId: 89190 } ]
An array of objects.对象数组。 I am trying to map over and extract the value of the shiftId
我正在尝试映射并提取shiftId
的值
What I do is object.map(el=> Object.values(el));
我所做的是object.map(el=> Object.values(el));
but this mapping returns the following structure because Object.values
returns an array unfortunately.但此映射返回以下结构,因为Object.values
不幸返回一个数组。
[ [ 89192 ], [ 89193 ], [ 89190 ] ]
Nested arrays with only one element.只有一个元素的嵌套数组。 How can I map over this to only back an array.我怎样才能映射到这个只支持一个数组。
If you want to extract the shiftId
property, just specify that you want to extract that particular property, rather than using Object.values
:如果要提取shiftId
属性,只需指定要提取该特定属性,而不是使用Object.values
:
const shiftIds = object.map(({ shiftId }) => shiftId);
Note that you have an array there - your code would be more understandable if you called the variable arrOfShiftObjs
or something like that, rather than calling it object
.请注意,您在那里有一个数组- 如果您调用变量arrOfShiftObjs
或类似的东西,而不是调用它object
,您的代码会更容易理解。
To extract multiple values from each item and put them into a single larger array, use flatMap
:要从每个项目中提取多个值并将它们放入一个更大的数组中,请使用flatMap
:
const arr = [{ shiftId: 89192, id: 'id' }, { shiftId: 89193, id: 'id' }, { shiftId: 89190, id: 'id' } ]; const values = arr.flatMap(Object.values); console.log(values);
Or, if the objects also contain other properties that you don't want to include, and you only want shiftId
and id
:或者,如果对象还包含您不想包含的其他属性,并且您只需要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);
Like the use of all newer functions, if you want to support browsers which don't have it yet, use a polyfill.就像使用所有较新的功能一样,如果您想支持还没有它的浏览器,请使用 polyfill。 Of course, you could also reduce
instead当然,你也可以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);
You could get the property from the first found value.您可以从第一个找到的值中获取该属性。
var array = [{ anonymous: { shiftId: 89192 } }, { anonymous: { shiftId: 89193 } }, { anonymous: { shiftId: 89190 } }], values = array.map(o => Object.values(o)[0].shiftId); console.log(values);
Using Object destructuring and Array.prototype.map使用对象解构和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.