Home > Blockchain >  How to convert JSON data to object that contains other objects?
How to convert JSON data to object that contains other objects?

Time:11-10

I want to apply my returned data to create a line chart in Vuejs

My data:

[{"A": 400},{"B": 1597},{"C": 1567}]

My template from vuejs:

<template>
    <line-chart :data="Mydata"></line-chart>
</template>

<script>
export default {
    data () {
        return {
            My data: null
        }
    }  
}
</script>

The line-chart only get data format like My data: {"A": 400,"B": 1597,"C": 1567} to draw a graph.

Expected output when added to App VUE

<template>
    <line-chart :data="Mydata"></line-chart>
</template>

<script>
export default {
    data () {
        return {
            My data: {"A": 400,"B": 1597,"C": 1567}
        }
    }  
}
</script>

CodePudding user response:

You can use a reducer function for this:

const data = [{
  "A": 400
}, {
  "B": 1597
}, {
  "C": 1567
}].reduce((acc, curr) => {
  Object.keys(curr).forEach(key => acc[key] = curr[key]);
  return acc
}, {})

console.log(data)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related