I have an array object with following data:
const arr = [
{
key: 'mykey1597855209',
integrity: 'sha512-T9JWj=='
},
{
key: 'mykey159785520915978552101597855212',
integrity: 'sha512-T9JWj=='
},
{
key: 'mykey15978552091597855210',
integrity: 'sha512-lcddfd=='
},
{
key: 'otherkey15978552091597855210',
integrity: 'sha512-abcdfd=='
}];
I want to create key
value
pair from the the arr[]
object such that integrity
becomes key and the key
becomes value
Desired Output is something like below:
{
"sha512-T9JWj==": [
"mykey1597855209",
"mykey159785520915978552101597855212"
],
"sha512-lcddfd==": [
"mykey15978552091597855210"
],
"sha512-abcdfd==": [
"otherkey15978552091597855210"
]
}
I have written following code:
const arr = [{ key: 'mykey1597855209', integrity: 'sha512-T9JWj==' }, { key: 'mykey159785520915978552101597855212', integrity: 'sha512-T9JWj==' }, { key: 'mykey15978552091597855210', integrity: 'sha512-lcddfd==' }, { key: 'otherkey15978552091597855210', integrity: 'sha512-abcdfd==' } ]; const result = Object.assign(...arr.map(a => ({ [a.integrity]: a.key }))); console.log(result)
You can transform it like this:
let map = {};
arr.forEach({ key, integrity } => map[integrity] = key);
You can use Object.fromEntries
:
const arr = [{key: 'mykey1597855209',integrity: 'sha512-T9JWj=='},{key: 'mykey159785520915978552101597855212',integrity: 'sha512-T9JWj=='},{key: 'mykey15978552091597855210',integrity: 'sha512-lcddfd=='},{key: 'otherkey15978552091597855210',integrity: 'sha512-abcdfd=='}]; let map = Object.fromEntries(arr.map(({_, integrity }) => [integrity, []])); arr.forEach(({key, integrity}) => map[integrity].push(key)); console.log(map);
Or reduce
:
const arr = [{key: 'mykey1597855209',integrity: 'sha512-T9JWj=='},{key: 'mykey159785520915978552101597855212',integrity: 'sha512-T9JWj=='},{key: 'mykey15978552091597855210',integrity: 'sha512-lcddfd=='},{key: 'otherkey15978552091597855210',integrity: 'sha512-abcdfd=='}]; let map = arr.reduce((acc, { key, integrity }) => { acc[integrity] = acc[integrity] || []; acc[integrity].push(key); return acc; }, {}); console.log(map);
arr.reduce((acc, curr) => {
acc[curr.integrity] = (acc[curr.integrity]) ?
[ ...acc[curr.integrity], curr.key ] :
[ curr.key ]
return acc;
}, {})
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.