0

How can I convert an array into a list of objects?

Turn

[
    {
        "currenttime":43481.46983805556,
        "moped":"30 minutes",
        "car":"1 hour"
    }
]

into

{
    "currenttime":43481.46983805556,
    "moped":"30 minutes",
    "car":"1 hour"
}

The data is retrieved from an external source and then the data edited using Vue.js

<script type="text/javascript">
    const app = new Vue({
    el: '#app',
    data: {   
        items: []
    },
    created: function() {
        fetch('https://example.com/delivery.json')
        .then(resp => resp.json())
        .then(items => {        
            this.items = items
        })
    }
    });
</script>

I had originally tried to output using an expression of {{ items.car }} and {{ items.0.car }} with no success

6
  • 2
    What's the difference between array and list of objects? What if you receive an array with two objects, do you want only the first one (meaning items[0])? Commented Jan 16, 2019 at 12:29
  • why would you do that ? Commented Jan 16, 2019 at 12:29
  • 1
    Side note: It's not the problem, but it's a problem: You're not handling errors in your fetch call, in two different ways: 1. You're not handling errors at all (you need to either add a catch handler, or propagate the promise to something that will have a catch handler), and 2. You're not checking .ok. Its' not just you, this second one is such a common mistake that I wrote it up in my anemic little blog. Commented Jan 16, 2019 at 12:32
  • Use v-for instead of getting single object Commented Jan 16, 2019 at 12:33
  • You need to show us your Vue HTML template. Use something like <div v-for="item in items">{{ item.car }}</div> instead of ditching the rest of the array. Commented Jan 16, 2019 at 12:35

1 Answer 1

1

Adding this, although not an ideal or correct solution does solve the issue for now.

this.items = items[0]

Sign up to request clarification or add additional context in comments.

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.