1

How can I convert an array that contains multiple objects to a single object

I want to convert something like this :

    [

      {
        'Kyber': {tokenSymbol: 'DAI', avgPrice: 1}
      },
      

      {
       'Bamboo Relay': {tokenSymbol: 'DAI',avgPrice: 1}
      }
   
    ]

To something like this :

{
    'Kyber': {tokenSymbol: 'DAI', avgPrice: 1},
   'Bamboo Relay': {tokenSymbol: 'DAI',avgPrice: 1}
}
2
  • 2
    Simply iterate the array and add the properties of each object to a single result. What have you tried? Where are you stuck? Commented Jul 17, 2020 at 23:57
  • Can an object have multiple key-value pairs? What should be done in that case? Commented Jul 18, 2020 at 0:01

2 Answers 2

3

use Array.reduce

const data = 
        [ { 'Kyber': { tokenSymbol: 'DAI', avgPrice: 1} } 
        , { 'Bamboo Relay': { tokenSymbol: 'DAI', avgPrice: 1} } 
        ] 
const result = data.reduce((a,c)=>
        {
        for (const [k,v] of Object.entries(c)) a[k]={...v} 
        return a
        }, {})
Sign up to request clarification or add additional context in comments.

Comments

0

You could achieve that by iterate through the array of object, and for each object, merge that object to the result object. Below solution could help you

const data = [
  {
    Kyber: { tokenSymbol: 'DAI', avgPrice: 1 }
  },
  {
    'Bamboo Relay': { tokenSymbol: 'DAI', avgPrice: 1 }
  }
]

const res = {}
data.forEach(obj => {
  Object.assign(res, obj)
})

console.log(res)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.