-1

I have this object schema:

{
    car: [
      {
         //Object data
      }
    ],
    motorcycle: [
      {
         //Object data
      }
    ],
    ...
}

My question is how I get all the objects from cars and motorcycles in one object like this:

Basically I want all key,value pairs from motorcycle and cars in one object –

{
   key1 : {//Object Data},
   key2 : {//Object Data},
}
warCommander
  • 392
  • 4
  • 19

1 Answers1

1

A possible approach using Object.entries and map and Object.fromEntries assuming that there is 1 element in the key array of original object

const a = {
    car: [
      {
       data1: 'data car'
      }
    ],
    motorcycle: [
      {
        data2: 'data cycle'
      }
    ],
}

let x = Object.fromEntries(Object.entries(a).map(([key,[val]],index)=> [`key${index+1}`,val]))

console.log(x)

If more than 1 objects in key arrays can do something like this

const a = {
    car: [
      {
       data1: 'data car 1'
      },
      {
       data2: 'data car 2'
      }
    ],
    motorcycle: [
      {
        data3: 'data cycle 3'
      }
    ],
}

//Object.entries in case you want access to car,motorcycle....
let x = Object.fromEntries(Object.entries(a).flatMap(([key,val])=> val).map((e,index)=>[`key${index+1}`,e] ))

//this should work if no need to access car,motocycle..
// let x = Object.fromEntries(Object.values(a).flatMap((val)=> val).map((e,index)=>[`key${index+1}`,e] ))
 
console.log(x)
cmgchess
  • 7,996
  • 37
  • 44
  • 62