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
What I do is object.map(el=> Object.values(el));
but this mapping returns the following structure because Object.values
returns an array unfortunately.
[ [ 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
:
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
.
To extract multiple values from each item and put them into a single larger array, use 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
:
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. Of course, you could also reduce
instead
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
let array = [{ anonymous: { shiftId: 89192 } }, { anonymous: { shiftId: 89193 } }, { anonymous: { shiftId: 89190 } }] let out = array.map(({anonymous: {shiftId}}) => shiftId) console.log(out)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.