P
P
Peter2020-05-08 00:06:02
JavaScript
Peter, 2020-05-08 00:06:02

How to output json content by key?

Goodnight. Please tell me how can I correctly display the JSON content based on the key that is stored in LocalStorage.
The API returns me this kind of JSON

let goods = [
    {
       "id":"1",
       "name":"Pizza",
       "cost":3
    },
    {
       "id":"2",
       "name":"Cola",
       "cost":5
    },
    {
       "id":"3",
       "name":"Tomatoes",
       "cost":6
    }]

In LocalStorage, I saved the product id and its quantity. The key is id and the value is the quantity of the item. I wrote two methods, one adds id and quantity to LocalStorage, the second one reads from LocalStorage.
{1: 3, 2: 2, 3: 1}
function addToCart(id) {
    if (cart[id]!=undefined) {
        cart[id]++;
    }
    else {
        cart[id] = 1;
    }
    localStorage.setItem('cart', JSON.stringify(cart) );
}

function getCartFromLS() {
    return JSON.parse(localStorage.getItem('cart'));
}

Then I try to pull out information on the product by the received id from LocalStorage
let cart = getCartFromLS();

    for(let key in cart){
        console.log(goods[key].name);
    }

I am getting console output.
Cola
Tomatoes
Uncaught TypeError: Cannot read property 'name' of undefined
Outputs only two objects on the third one swears. And they do not match by id.
How to generate a correct conclusion? What would output by id from LocalStorage?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-05-08
@Morpheus_God

In JS array indexes start from zero, you are trying to access goods[3] which does not exist.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question